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.

Calgary

1700, 308 4th Avenue SW
Calgary, AB T2P 0H7
Canada
403.242.4361

info.calgary@arcurve.com

Houston

5090 Richmond Avenue
Houston TX, 77056
USA
713.422.2135

info.houston@arcurve.com

© 2024 Arcurve. All rights reserved.