RxJS: Hot and Cold Observables
What is RxJS?
RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.
What is an Observable?
A representation of any set of values over any amount of time. This the most basic building block of RxJS.
- Array of values over an amount of time.
- A data stream
- Just a function, with a few special characteristics.
- It takes in an “observer” (an object with “next”, “error” and “complete” methods on it)
- Returns cancellation logic (unsubscribe)
- Connects observer to "producer"(source of values)
- Observables can be either hot or cold
- Observables created using the of, from, range, interval and timer operators will be cold.
- Observables created with the fromEvent operator for either user events or WebSocket events will be hot.
- Producer created by the observable inside it
- Data emits on subscribe to observable
- Completes data stream itself
- All subscriptions are independent
- Re-emits the whole values for new subscriber
- Producer created outside the observable
- Data emits as soon as observable created
- need extra logic to complete the subscription
- All subscriptions share values
- Data can be lost if no subscriber
Making cold observable hot
publish() : ConnectableObservable
- Start emitting when at least one subscriber
- Publish() along with refCount()
- Shortcut share()
- Hot observable -> Movie at the Cinema
- Cold observable -> Movie with Netflix
- ‘Warm’ observable -> Movie with friends
Thank you :)
RXJS: Hot and Cold Observables
By Zenab Saleem