concat
signature: concat(observables: ...*): Observable
concat(observables: ...*): Observable
Subscribe to observables in order as previous completes
💡 You can think of concat like a line at a ATM, the next transaction (subscription) cannot start until the previous completes!
💡 If throughput, not order, is a primary concern, try merge instead!
Why use concat
?
concat
?The concat operator is best used when you need to combine multiple observables, but you want their emissions to be in a specific order, one after the other. It's like putting together a puzzle where the pieces must come together sequentially to create the full picture. An example of this can be seen in a real-world scenario, like downloading and displaying several images in the correct order, where you don't want the next image to load until the current one is fully loaded.
Keep in mind that concat will only start emitting values from the next observable once the previous one has completed. This means that if one of your observables never completes, the subsequent observables will never emit any values. This behavior can be a gotcha, as there will be no output and no error, but one (or more) of your inner observables might not be functioning as intended, or a subscription is not being set up correctly.
In contrast, if you need to combine observables that emit values concurrently, or you require the latest values from multiple observables whenever any of them emit a new value, combineLatest or withLatestFrom might be more suitable options.
Examples
Example 1: Basic concat usage with three observables
( StackBlitz )
Example 2: Display message using concat with delayed observables
( StackBlitz )
Example 3: (Warning!) concat with source that does not complete
( StackBlitz )
Related Recipes
Additional Resources
concat 📰 - Official docs
concat - In Depth Dev Reference
Combination operator: concat, startWith 🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/concat.ts
Last updated