I have the following requirement:
- execute HTTP call A
- wait for A to finish
- execute HTTP call B
- do not wait for B to finish
- return result of HTTP call A
This seemed like a good case for the Rxjs tap
operator, since call B is considered a 'side effect'. This is the code (subscribing to the result of this function is done elsewhere in the code):
public call(): Observable<any> {
return this.http.get('/operation/a').pipe(
tap(() => {
this.http.get('/operation/b');
})
);
}
I noticed call B is not getting executed, because no one is subscribing to it. The following code fixes the problem:
public call(): Observable<any> {
return this.http.get('/operation/a').pipe(
tap(() => {
this.http.get('/operation/b').subscribe();
})
);
}
However, this feels icky, since we now have 2 subscriptions: one inside the tap
, the other one when calling this method. Technically it is not a problem, since the observable within the tap
will complete and therefore it doesn't need to be unsubscribed, but if feels off.
I do not know how else to implement a 'fire and forget' without waiting for the results of call B. Is there a 'proper' way to do so with Rxjs?