RxJS wait for an observable to complete in its entirety

11,683

Solution 1

you can try last operator

obsA.pipe(last(),mergeMap(()=>obsB)).subscribe()

Solution 2

More "clean" solution would be using just concat because it subscribes to Observables one by one only when the previous one completes:

import { concat } from 'rxjs';

concat(observableA, observableB)
  .subscribe(...)

If you want to ignore all values coming from observableA you can use ignoreElements() when passing it to concat (observableA.pipe(ignoreElements())).

Share:
11,683
Nick
Author by

Nick

Updated on June 25, 2022

Comments

  • Nick
    Nick almost 2 years

    I'm trying to get an Observable to complete in its entirety (meaning the Complete function is called) before the next Observable executes. I've tried many different things, but the closest I've gotten is this:

    function() {
      observableA.subscribe(
        (value) => { },
        (err) => { },
        () => {
          createObservableB();
        }
      );
      return observableB; // ????
    }
    

    But I need to return the result from createObservableB() from this function. Again, createObservableB cannot be called until every single value in observableA has been iterated over in its entirety.

    Thanks for any help!

  • Nick
    Nick over 5 years
    Thanks for your answer, but this doesn't solve my situation. If you have functionA(functionB(), functionC()), JavaScript will invoke functionB, then functionC and pass the returned value from both functions to functionA. Therefore, you're calling functionC (in this case createObservableB()) before you've even started iterating over the values from observableA. I need to completely exhaust observableA before createObservableB can even be called.
  • Nick
    Nick over 5 years
    This is exactly what I needed, thanks! The function being passed into mergeMap doesn't execute until the last item from the first observable has completed.
  • serg06
    serg06 over 3 years
    last() only returns the final value; if you want all the values, you can use scan() to group them into an array then last() to output the finished array