The Subject instances
The Subject
instances are both Observable
instances and Observer
instances. Like Observable
instances, they can have multiple Observer
instances, receiving the same notifications. That's why they can be used to turn cold Observable
instances into hot ones. Like Observer
instances, they give us access to their onNext()
, onError()
, or onCompleted()
methods.
Let's look at an implementation of the preceding hot interval examples, using a Subject
instance:
Observable<Long> interval = Observable.interval(100L, TimeUnit.MILLISECONDS); // (1)
Subject<Long, Long> publishSubject = PublishSubject.create(); // (2)
interval.subscribe(publishSubject);
// (3)
Subscription sub1 = subscribePrint(publishSubject, "First");
Subscription sub2 = subscribePrint(publishSubject, "Second");
Subscription sub3 = null;
try {
Thread.sleep(300L);
publishSubject.onNext(555L); // (4)
sub3 = subscribePrint(publishSubject, "Third"); // (5)
Thread.sleep(500L);
}
catch (InterruptedException...