RxJS Functions (Part 4)

Corey Pyle
2 min readJan 11, 2019

--

concat

It’s a cat behind bars. Con cat…

This one was fun. Since I’m using interval to setup an Observable, I end up with one that’s cold. Since my marble component subscribes to the Observable passed to it, it was creating a new ‘interval’ for each subscription. Each of my marbles was firing off willy-nilly rather than properly rendering the example I had in mind. To handle this I took advantage of an operator called share which, in this case, shared the original interval with each new subscription instead of creating a new one.

This solved my issue, but exposed another one. The whole point of concat is that it does not subscribe to a subsequent Observable until the previous one completes. My existing animations did not have any visualization of this, so now I’ve added a class that turns down the opacity on a marble when its Observable has completed. I like the effect.

concat

Creates an output Observable which sequentially emits all values from given Observable and then moves on to the next.

Note: there are two ‘concat’ functions. One is this one, the other is the deprecated operator version which I will not cover.

Use Case

concat would be used when you want to ensure one stream has completed before you start listening to the next one. An example could be a media playlist. The playlist has 3 audio clips, each of variable length. It might look something like this:

Something worth noting in this example: unlike the StackBlitz above, each of these ‘audio clip’ Observables is intentionally left ‘cold’. Every time an observer subscribes to the Observable created by concat, the playlist starts over. If instead you wanted new subscribers to pickup from the current playback location, you could implement share for each clip.

Thanks for reading. Stay tuned for Part 5, and be sure to check out the previous articles.

--

--