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

前端 未结 2 1375
小鲜肉
小鲜肉 2020-12-25 08:52

My Angular 2 application has 2 methods (GetCategories() and GetCartItems()) in a service , and both of these methods return Observable

相关标签:
2条回答
  • 2020-12-25 09:16

    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

    0 讨论(0)
  • 2020-12-25 09:21

    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;
        });
    
    0 讨论(0)
提交回复
热议问题