如何解决RXJS将单个可观测值转换为可观测值数组
我有一个API( getNewStories ),它以numbers(ids)
数组的形式返回数据,例如[1,2,3,4 ...]。
还有另一个使用number(id)
并提供其详细信息的API( getItem )。
我该如何使用rxjs运算符来完成此操作,这样我只应订阅一次,它就会为我提供带有这些ID的记录数组?
我可以使用2个订阅来完成此操作,但是我想要一个。可能吗?如果是的话,怎么办?
this.hnService.getNewStories().subscribe(data => {
// data is [1,4,5]
// create an array of observables for all the ids and get the record for that id
const observables = data.map(item => this.hnService.getItem(item));
// use forkJoin to combine the array to single results variable
forkJoin(...observables).subscribe(results => {
this.stories = results;
});
});
为此,我必须同时订阅两个API。
解决方法
您使用forkJoin
朝着正确的方向前进:
this.hnService.getNewStories()
.pipe(
concatMap(data => {
const items$ = data.map(item => this.hnService.getItem(item));
return forkJoin(...items$);
}),)
.subscribe(allItems => ...);
forkJoin
将等到所有源Observable都完成,然后才将所有结果作为单个数组发出。
我认为您可以使用像这样的展平运算符来实现这一目标。
<div class="container">
<img src="https://picsum.photos/id/237/200/300" height="600" class="l3"/>
<div class="centered" style= "color: lightblue" >This is to certify that the building described herein has been inspected and confirms substantially to the approved drawings & to the requirements of all the applicable codes,laws,rules and regulations that were in place at the time of the issue of this certificate.</div>
</div>
<img src="https://picsum.photos/id/237/200/300" style = width="100" height="100" class="l1"/>
<img src="https://picsum.photos/id/237/200/300" style = width="100" height="100" class="l2"/>
其他选项可以是创建两个可观察的流并使用CombineLatest。
,您可以按照以下代码片段的方式进行实现:(是的,AppBar(
backgroundColor: Colors.transparent,centerTitle: false,brightness: Brightness.dark,title: Container(
width: 150,child: Row(
children:[
IconButton(icon:Icons.back_arrow,onpressed:() =>
Navigator.pushReplacementNamed(context,'/Your Home_Screen');
),Text('tuloung duloung',style: TextStyle(
fontWeight: FontWeight.w400,color: theme.primaryColor,)),]
),),automaticallyImplyLeading: false,iconTheme: IconThemeData(
color: theme.primaryColor,actions:[ Container(
width: 150,child: FlatButton.icon(
label: Text('Done'),icon: Icon(Icons.check_circle),onPressed: () => {
setState(() {
takingsnap = true;
_captureImage();
})
}),]
),
展平了包含数组的可观察对象,有关更多解释,请参见关于Best way to “flatten” an array inside an RxJS Observable
的mergeAll
帖子)
@Martin's
您可以尝试运行以下代码段:
getNewStories().pipe(mergeAll(),concatMap(this.getItem),toArray()).subscribe()
const { of } = rxjs;
const { concatMap,toArray,mergeAll } = rxjs.operators;
function getItem(x) {
return of({ item : x })
}
of([1,2,3,4])
.pipe(
mergeAll(),concatMap(getItem),toArray()
)
.subscribe(console.log)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。