28. merge and concat: merge or queue
Combining several streams
Sometimes you already have two or more ready Observables and need to merge them into one. merge and concat are two strategies for that.
merge — combine "as they arrive"
merge(a$, b$) subscribes to both sources at once. Values pass through as soon as they appear, no matter which source sent them.
concat — a strict sequence
concat(a$, b$) subscribes only to the first source. When it fully completes, it subscribes to the second. The second's values won't appear until the first has finished.
concat(cache$, server$)
// first everything from cache$ → complete → then everything from server$
A typical concat scenario
"Show the cache first, then refresh from the server." The user sees a result instantly, and a moment later it updates with fresh data.
A trap
If the first stream never completes (an interval without take, say), the second will never start.
Your task
- Replace
const result$ = cache$;withconst result$ = concat(cache$, server$);. - First
Cache Datacomes out, then — after a delay —Server Data.
Deterministic check
This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.
const { of, timer, concat, map } = Rx;
const cache$ = of('Cache Data');
const server$ = timer(30).pipe(map(() => 'Server Data'));
const result$ = concat(cache$, server$);