Cold Observable
- Creation of Producer: A cold Observable creates a new data producer (the source of the emitted values) for each new subscriber.
- Timing of Emission: The emission of values starts only when a subscriber subscribes to the Observable.
- Data Stream: Each subscriber receives an independent stream of data from the beginning of the sequence.
- Behavior: Cold Observables are unicast. Each subscription triggers a new execution of the producer.
- Analogy: Think of a music CD. When someone wants to listen, they put the CD in the player, and the music starts from the beginning for that individual. Each person listening to the same CD starts the music from the beginning independently.
- Examples:
- HTTP requests (each subscription triggers a new request).
- Reading a file.
- Generating a sequence of numbers using
Observable.create
orObservable.interval
without any sharing operators.
Hot Observable
- Creation of Producer: A hot Observable has its data producer created outside of the Observable itself, often before any subscription occurs.
- Timing of Emission: The emission of values happens regardless of whether there are any subscribers. Subscribers who join later will only receive the values emitted from the point of their subscription onwards. They might miss previously emitted values.
- Data Stream: All subscribers share the same underlying stream of data.
- Behavior: Hot Observables are multicast. Multiple subscribers share a single execution of the producer.
- Analogy: Think of a radio broadcast. The radio station transmits its signal continuously. Listeners who tune in at different times will hear the broadcast from the moment they connect; they won't hear what was broadcast before they tuned in.
- Examples:
- DOM events (like mouse clicks or movements).
- WebSockets.
- Subjects (in RxJS), which are both Observables and Observers.
- Timers or intervals that start independently of subscription.
Here's a table summarizing the key differences:
Feature | Cold Observable | Hot Observable |
---|---|---|
Producer Creation | Created per subscriber | Created outside the Observable |
Emission Start | Starts upon subscription | Starts regardless of subscription |
Data Stream | Independent stream per subscriber | Shared stream among all subscribers |
Behavior | Unicast (one producer per subscriber) | Multicast (one producer shared by many subscribers) |
Missed Values |