RxJava Operators: replay()

November 19, 2018


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)

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


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

András Döbröntey

About the Author

András Döbröntey

Leave a Comment: