RXJS将单个可观测值转换为可观测值数组

时间:2020-08-11 13:50:08

标签: javascript angular rxjs

我有一个API( getNewStories ),它以numbers(ids)数组的形式返回数据,例如[1,2,3,4 ...]。 还有另一个使用number(id)并提供其详细信息的API( getItem )。

我该如何使用rxjs运算符来完成此操作,这样我只应订阅一次,它就会为我提供带有这些ID的记录数组?

我可以使用2个订阅来完成此操作,但是我想要一个。可能吗?如果是的话,怎么办?

this.hnService.getNewStories().subscribe(data => {
  // data is [1,2,3,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。

3 个答案:

答案 0 :(得分:1)

您使用forkJoin朝着正确的方向前进:

this.hnService.getNewStories()
  .pipe(
    concatMap(data => {
      const items$ = data.map(item => this.hnService.getItem(item));
      return forkJoin(...items$);
    }),
  )
  .subscribe(allItems => ...);

forkJoin将等到所有源Observable都完成,然后才将所有结果作为单个数组发出。

答案 1 :(得分:0)

我认为您可以使用像这样的展平运算符来实现这一目标。

<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。

答案 2 :(得分:0)

您可以按照以下代码片段的方式进行实现:(是的,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帖子)< / p>

@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)