Subscribe to multiple Observables (like chaining then() in Promises)

孤人 提交于 2019-11-30 00:49:53

Looks like GetCartItems doens't depend on GetCategories. Then you can use zip:

Observable
    .zip(
        this.appService.GetCategories()
        this.appService.GetCartItems()
    )
    .catch(err => this.toaster.error(err))
    .subscribe(([categories, cartItems]) => {
        this.appService.categories = categories;
        this.appService.cart = cartItems;
    });

This is most typically done with concat(), concatMap() or eventually concatAll() depending on your usecase and whetrher you need to call both services in order or not.

function GetCategories() {
    return Observable.timer(1000).do(() => console.log('GetCategories()'));
}

function GetCartItems() {
    return Observable.timer(1000).do(() => console.log('GetCartItems()'));
}

console.log('start...');

GetCategories()
  .concatMap(() => GetCartItems())
  .subscribe(() => console.log('done'));

This prints to console:

start...
GetCategories()
GetCartItems()
done

Each item is delayed to show these are called in order one after another.

If you don't need to keep the same order you can use merge() or mergeMap().

See live demo: https://jsbin.com/wawajob/1/edit

Note that using zip() might have undesired behavior. See https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/zip.md

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!