ReplaySubject takes an entirely different approach compared to Publish and BehaviorSubject instances . It records all the values that it received and, upon a new subscription to itself, it will replay all the captured values to the new subscription.
Take a look here:
Subject<String> subject = ReplaySubject.create();
Observable.interval(0, 1, TimeUnit.SECONDS)
.map(Objects::toString)
.subscribe(subject);
Thread.sleep(3100);
subject.subscribe(v -> log(v));
In this block, we have created a ReplaySubject with the following:
Subject<String> subject = ReplaySubject.create();
Also, we have made it receive values from Observable.interval():
Observable.interval(0, 1, TimeUnit.SECONDS)
.map(Objects::toString)
.subscribe(subject);
Next, we wait for three seconds with this:
Thread.sleep(3100);
We subscribe to the created subject with the following:
subject.subscribe(v -> log(v));
Upon subscription, it will immediately print all the three items that were emitted until then:
main:0
main:1
main:2
main:3
RxComputationThreadPool-1:4
RxComputationThreadPool-1:5
RxComputationThreadPool-1:6
Afterward, it will just continue printing the items received from the original Observer. ReplaySubject will be useful when there is a need to replay the entire history of received items. For example, it can come in handy if anyone is working with the Event Sourcing or a command pattern.
Event Sourcing is a pattern where the resulting state of an object can always be recomputed by replaying events that lead to the current state. More information about this is available at https://msdn.microsoft.com/en-us/library/dn589792.aspx.
Command pattern usually defines changes to objects as commands and modifications to objects are done using only commands. This is very similar to Event Sourcing but more about this can be found at https://en.wikipedia.org/wiki/Command_pattern.