RxJS and Incomplete Streams

Jeff
November 17, 2018
Blog

I had a long chain of observables combined using switchMap, with a finally() method at the end. My finally() method was not being executed when I expected it to, and it wasn’t immediately obvious why. Turns out it was because the observable was never completing. The first observable in the chain was one I manually created from a subject, like this:

blah(): Observable { 
  const confirmed = new Subject();  
  
  // do some stuff here that will emit values to the subject. 
  return confirmed.asObservable();
}

Then I was chaining the observable with some API requests after blah(), followed by doing something when it all finished:

blah()
  .switchMap(result => doSomeApiRequest())
  .switchMap(x => doSomeOtherApiRequest())
  .finally(y => doSomethingWhenDone());

doSomethingWhenDone will only execute here if something fails in the chain. On the success path, it never will. This is because the subject I created has potential to emit values forever, which results in a stream that is never completed.

In my situation, I only care about the first value in the stream. I can therefore complete the stream by taking only the first value emitted by the Subject:

blah(): Observable { 
  const confirmed = new Subject();  
  
  // do some stuff here that will emit values to the subject. 
  return confirmed.asObservable().first();
}

Very subtle and makes sense when you consider the larger context. At the time though, there was a bit of head scratching to understand what was happening.

Championing Your Business.
Driving Change.
Delivering Excellence.
That's the Arcurve Advantage.

Let's talk about your project

Book Now