BACK
Lessons41. share: one source for several subscribers
Lessons · 41

41. share: one source for several subscribers

Cold vs Hot — an important pair of ideas

A cold Observable runs its logic anew for each subscriber. of, from, defer, an HTTP request — all cold. Subscribe twice and you get two requests.

A hot Observable is one source for everyone. Every subscriber sees the same values. A Subject is the typical example.

share — simple multicast

share() turns a cold Observable hot for as long as there's at least one subscriber. Under the hood it uses a Subject, but it spares you the manual work.

cold$.pipe(share())
// two subscribe → one cold run → both get the same values

Glossary

  • Multicast — broadcasting one stream to many subscribers.
  • Unicast — a separate stream per subscriber. Cold = unicast.

Your task

  1. In the cold$ pipe, add share().
  2. The check confirms the start counter starts equals 1 — the cold source ran only once, despite two subscribers.

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.

Solution spoiler · click to reveal
const { Observable, share } = Rx;

let starts = 0;

const cold$ = new Observable(subscriber => {
  starts += 1;
  const subscription = cold('20ms a|', { a: 'value' }).subscribe(subscriber);
  return () => subscription.unsubscribe();
});

const shared$ = cold$.pipe(
  share()
);
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...