I have three observables I would like to combine into a single stream. However the third observable requires a property from the first observable -- is it possible to combine all three to avoid nested subscribes (for the sake of clarity)?
Observable.combineLatest(this.fooService.model, this.barService.model)
.subscribe(result => {
//do work
this.bazService.anotherObservable(result[0].someProperty)
.subscribe(anotherResult => {
//do more work
});
});
You can use switchMap and map to do what you want:
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));
Whenever the combined foo and bar observables emit a value, the baz service will be called and its result will be futher combined.
Note that switchMap will abandon pending baz calls if the foo or bar observables re-emit. If you don't want that behaviour and always want the baz result to be emitted, use concatMap instead of switchMap.
Another option is to use mergeMap instead of concatMap - the latter will guarantee that the order of the baz calls will be preserved, the former won't.