RxJava Operators: cache()

November 26, 2018

cache()

The cache() operator can be used to cache all emissions indefinitely. It will subscribe to the source on the first downstream subscribing Observer.

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {

        Observable<String> myCachedSource = Observable.just("a", "b", "c", "d", "e")
                                                      .scan((total, next) -> {
                                                          System.out.println(String.format("Calculating %s + %s", total, next));
                                                          return total + next;
                                                      })
                                                      .cache();

        //this subscription will initialize the cache
        myCachedSource.subscribe(System.out::println);

        //this subscription will use the cached items
        myCachedSource.subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami