Search code examples
rxjsrxjs6rxjs-observables

How do I switch between two Observables in order and have the subscription fire twice?


I am using RxJS. I have two Observables (API calls) that return a different amount of information for the same array. I want to switch between the Observables and have the subscription recognize both results, i.e. fire each time a value is returned.

Here's an example using Typescript (this does not work):

let foo = [];
const callOne$ = this.service.getSomeData$; // this should take 0.5 seconds
const callTwo$ = this.service.getAllTheData$; // this should take 6 seconds

callOne$.pipe(
    switchMap(data => data.length > 0 ? callTwo$ : of(data)
).subscribe(data => {
    console.log(data); // this fires once but I want it to fire twice
    foo = data;
});

The above example retrieves callOne$, then retrieves callTwo$, and then gives me the result. Instead I want the results of both in order. How would I subscribe to the Observables so that the first result is received and then updated by the second call?


Solution

  • I discovered the best result is to use concat(), which responds to Observable results in order.

    In other words:

    concat(callOne$, callTwo$)
    .subscribe(data => {
        console.log(data); // this will fire twice
        foo = data;
    });
    

    This code will return two results for data, updating the variable in the order of the concat() list.