...

/

Reactive Everything: Multicasting

Reactive Everything: Multicasting

Learn how to share the same underlying source with multiple observers.

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.

Press + to interact
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 ...