Reputation: 137
I'm just getting into rxjs and currently learning combineLatest. I get the idea that it combines multiple observable into one. I am wondering if it is possible to still use combineLatest when my 2nd observable is dependent of the value of the first.
For example, my first call will get me a user ID. Then I need to pass that user ID into the 2nd call. Is it possible to use combineLatest in this situation?
Upvotes: 3
Views: 1606
Reputation: 1103
The quick answer is no - combineLatest will only emit value after all of the observables emit at least once. In your case you can use:
http.get('/my-url-for-id').pipe(
flatMap(response => this.http.post('/some-other-url', response.id))
)
the second http GET
will be executed after the first one.
If you want to return both the results from the first call AND the second one, you can really use combineLatest
like:
this.http.get('/id').pipe(
flatMap(response => combineLatest(
[
of(response.id),
this.http.post('/some-other-url', response.id)
]
)
)
The resulting observable will be of type Observable<[string, {}]>
where {}
is a type of the second post
request
Upvotes: 3
Reputation: 893
No.You cant use combineLatest when two observable depend on each other. The scenario you explained can be handled by switchMap. It will take the value of the first observable and subscribe the second observable
Upvotes: 0