Search⌘ K
AI Features

Reactive Everything: Multicasting

Understand how to convert a cold Observable to a hot Observable using RxJava's .publish() and .share() operators. Explore multicasting with ConnectableObservable, and learn how Subjects serve as both Observers and Observables. This lesson covers practical approaches to efficiently share data across multiple subscribers in Android reactive programming.

Using .publish()

The simplest mechanism to convert a given cold Observable to a hot Observable is by using the method .publish(). Calling .publish() returns a ConnectableObservable, which is a special type of Observable wherein each Observer shares the same underlying resource. In other words, using .publish(), we are able to multicast, or share to multiple observers.

Subscribing to a ConnectableObservable, however, does not begin emitting items.

Java
ConnectableObservable<Integer> observable = Observable.create(source -> {
Log.d(TAG, "Inside subscribe()");
for (int i = 0; i < 10; i++) {
source.onNext(i);
}
source.onComplete();
}).subscribeOn(Schedulers.io()).publish();
observable.subscribe(i -> {
// This will never be called
Log.d(TAG, "Observer 1: " + i);
});
observable.subscribe(i -> {
// This will never be called
Log.d(TAG, "Observer 2: " + i);
});

For ...