【问题标题】:Call Observable.subscribe() in sequence依次调用 Observable.subscribe()
【发布时间】:2020-04-30 07:41:11
【问题描述】:

我有一个对象数组,我想遍历数组并为每个元素调用服务,但是对于每个元素,我只想在当前调用为时调用下一个元素成功完成,除非阻止其余的。

    onUpload(items: MyItem[]) {
      items.forEach(i => {
        myService.doSomething(i).subscribe(response => {
          // do something with the success item i
          // do the next call for the next item 
        }, error => {
          // handle the error
        })
      })

     }

是否可以在序列模式下调用 Observables 而不是并行?

【问题讨论】:

标签: angular rxjs observable


【解决方案1】:

使用from 从数组中发出值,然后使用contactMapsequentially execute observables

import { from } from 'rxjs';
import { concatMap } from 'rxjs/operators';

onUpload(items: MyItem[]) {
  from(items)
    .pipe(
       concatMap(item => myService.doSomething(i))
    )
    .subscribe(response => {/* do something with response */});
}

【讨论】:

    【解决方案2】:

    使用来自rxjsconcat。文档在这里https://www.learnrxjs.io/learn-rxjs/operators/combination/concat

    代码如下:

    onUpload(items: MyItem[]) {
      const observableArray = items.map(i => myService.doSomething(i));
      concat(...observableArray).subscribe(
        () => { /* Some logic */ },
        (err) => { /* Some logic */ },
      );
    }
    

    【讨论】:

      【解决方案3】:

      我觉得会更优雅

      onUpload(items: MyItem[]) {
        from(items)
        .pipe(mergeMap((item) => myService.doSomething(item)))
        .subscribe(
          () => console.log(finish),
          (err) => console.log('error happens', err),
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        相关资源
        最近更新 更多