Java.Reactive.Explain the difference between Hot and Cold Observable

Understanding the difference between Hot and Cold Observables is crucial to mastering RxJava and reactive programming in general — especially when working with time-sensitive or shared data sources.

Let’s break it down clearly and visually 👇

❄️ Cold Observable

📌 What it is:

A Cold Observable doesn’t start emitting items until an observer subscribes.
Every subscriber gets its own independent sequence.

🔁 Think of it like:

A Netflix show — each person watches from the beginning when they hit “Play.”

🧪 Example:

Observable<Integer> cold = Observable.create(emitter -> {
    System.out.println("New subscription");
    emitter.onNext(1);
    emitter.onNext(2);
    emitter.onComplete();
});

cold.subscribe(i -> System.out.println("Subscriber 1: " + i));
cold.subscribe(i -> System.out.println("Subscriber 2: " + i));

✅ Output:

New subscription
Subscriber 1: 1
Subscriber 1: 2
New subscription
Subscriber 2: 1
Subscriber 2: 2

Each subscriber triggers a new emission from scratch.


🔥 Hot Observable

📌 What it is:

A Hot Observable starts emitting regardless of subscribers.
Subscribers only receive what is currently being emitted, not the full history.

🔁 Think of it like:

A live radio broadcast — tune in late, and you miss what’s already been played.

🧪 Example (RxJava + PublishSubject):

PublishSubject<String> hot = PublishSubject.create();

hot.subscribe(s -> System.out.println("Subscriber 1: " + s));

hot.onNext("One");
hot.onNext("Two");

hot.subscribe(s -> System.out.println("Subscriber 2: " + s));  // Joins late

hot.onNext("Three");

✅ Output:

Subscriber 1: One
Subscriber 1: Two
Subscriber 1: Three
Subscriber 2: Three
  • Subscriber 2 missed “One” and “Two” because it subscribed too late.
  • The stream is already “hot” and ongoing.

🔍 Summary Table

FeatureCold ObservableHot Observable
Emission TimingStarts on subscriptionStarts on creation or trigger
Per SubscriberIndependent streamsShared stream
Late SubscribersGet full sequence from startGet only current/live items
Use CaseAPIs, file reads, deferred opsUI events, sensor data, sockets
Rx TypesObservable, Single, FlowableSubject, ConnectableObservable, Shared Flow

🧠 Bonus: Making Cold Observable Hot

You can “heat up” a cold observable using .publish() and .connect():

Observable<Long> cold = Observable.interval(1, TimeUnit.SECONDS);
ConnectableObservable<Long> hot = cold.publish();
hot.connect(); // starts emitting

hot.subscribe(i -> System.out.println("Sub 1: " + i));

Thread.sleep(3000);

hot.subscribe(i -> System.out.println("Sub 2: " + i)); // joins late
This entry was posted in Без рубрики. Bookmark the permalink.