Reactive Extensions (Rx.NET) is used to handle asynchronous data streams in .NET applications.
One of the most important concepts to understand is the difference between Cold Observables and Hot Observables.
What is an Observable?
An Observable is a data stream that we can subscribe to and receive values over time.
IObservable<int> stream = Observable.Range(1, 3); stream.Subscribe(x => Console.WriteLine(x));
Cold Observables (Simple Meaning)
- Starts only when someone subscribes
- Each subscriber gets separate execution
- Default behavior in Rx.NET
- Best used for API calls, database queries, file reading
Simple Cold Observable Example
var cold = Observable.Range(1, 3);
cold.Subscribe(x => Console.WriteLine("Subscriber 1: " + x));
cold.Subscribe(x => Console.WriteLine("Subscriber 2: " + x));
Here execution happens twice because each subscriber gets a new stream.
Hot Observables (Simple Meaning)
- Runs continuously and shares data
- All subscribers receive the same live stream
- Execution happens only once
- Best used for event streams, real-time systems, UI events
Simple Hot Observable Example
var hot = Observable.Interval(TimeSpan.FromSeconds(1))
.Publish()
.RefCount();
hot.Subscribe(x => Console.WriteLine("Subscriber 1: " + x));
hot.Subscribe(x => Console.WriteLine("Subscriber 2: " + x));
Now both subscribers share the same execution.
Even Simpler Way Using Share()
var hot = Observable.Interval(TimeSpan.FromSeconds(1))
.Share();
Share() is a shortcut for Publish().RefCount().
Real Life Example
- Cold Observable: Watching a recorded video separately
- Hot Observable: Watching live TV broadcast
Cold vs Hot Comparison
| Feature | Cold | Hot |
|---|---|---|
| Execution | Per subscriber | Shared |
| Data Type | Fresh data | Live data |
| Performance | Lower | Higher |
| Use Case | API / Database | Streaming |
Best Practices
- Use Cold Observables for request-based operations
- Use Hot Observables for real-time streaming
- Share expensive operations to avoid duplicate execution
Conclusion
Understanding Cold vs Hot Observables is essential for building scalable reactive applications.
Choosing the correct type helps avoid duplicate processing and improves system performance.
Technology: Rx.NET | Reactive Programming