2017-03-21 25 views
2

我有三個觀察對象我想合併成一個流。然而,第三個可觀察元素需要第一個可觀察元素的屬性 - 是否可以將所有三個元素結合起來以避免嵌套訂閱(爲了清晰起見)?當一個observable取決於另一個observable的結果時,避免與combine最近的嵌套訂閱

Observable.combineLatest(this.fooService.model, this.barService.model) 
    .subscribe(result => { 
    //do work 

    this.bazService.anotherObservable(result[0].someProperty) 
     .subscribe(anotherResult => { 
     //do more work 
     }); 
    }); 

回答

3

您可以使用switchMapmap做你想做什麼:

Observable 
    .combineLatest(this.fooService.model, this.barService.model) 
    .switchMap(([foo, bar]) => { 
    return bazService 
     .anotherObservable(foo.someProperty) 
     .map((baz) => [foo, bar, baz]); 
    }) 
    .subscribe(([foo, bar, baz]) => console.log(foo, bar, baz)); 

每當結合foobar觀測發射的值,則baz服務將被調用,其結果將是進一步結合。

請注意,如果foobar重新發射,switchMap將放棄等待baz調用。如果您不想要這種行爲並始終希望發射baz結果,請使用concatMap而不是switchMap

另一種選擇是使用mergeMap而不是concatMap - 後者將保證baz調用的順序將被保留,前者不會。

+0

真棒回答! – snorkpete

相關問題