ReplaySubject is similar to PublishSubject followed by a cache() operator. It immediately captures emissions regardless of the presence of downstream Observers and optimizes the caching to occur inside the Subject itself:
import io.reactivex.subjects.ReplaySubject;
import io.reactivex.subjects.Subject;
public class Launcher {
public static void main(String[] args) {
Subject<String> subject =
ReplaySubject.create();
subject.subscribe(s -> System.out.println("Observer 1: " + s));
subject.onNext("Alpha");
subject.onNext("Beta");
subject.onNext("Gamma");
subject.onComplete();
subject.subscribe(s -> System.out.println("Observer 2: " + s));
}
}
The output is as follows:
Observer 1: Alpha
Observer 1: Beta
Observer 1: Gamma
Observer 2: Alpha
Observer 2: Beta
Observer 2: Gamma
Obviously, just like using a parameterless replay() or a cache() operator, you need to be wary of using this with a large volume of emissions or infinite sources because it will cache them all and take up memory.