RxJava Operators: replay()

November 19, 2018

replay()

The replay() operator can be used to keep previous emissions and then emit them again when a new Observer comes in the scope.
It returns a ConnectableObservable, so it will multicast the emissions and also emit the previous items.
In the example below the first Observer will start thanks to the autoConnect() on the Observable, then after some time the second Observer also starts. At this point the previous emissions are repeated immediately for the second Observer and then the new items are being multicast to both.

import io.reactivex.Observable;

import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        Observable<Long> mySource = Observable.interval(1, TimeUnit.SECONDS)
                                              .replay()
                                              .autoConnect();

        mySource.subscribe(x -> System.out.println(String.format("Observer 1: %d", x)));

        Thread.sleep(3500);

        mySource.subscribe(x -> System.out.println(String.format("Observer 2: %d", x)));

        Thread.sleep(3000);
    }
}
András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami