Caching data with Observable.cache

We can use caching to cache the response in the memory and then, on the next subscription, instead of requesting the remote server again, to use the cached data.

Let's change the code to look like this:

String url = "https://api.github.com/orgs/ReactiveX/repos"; Observable<ObservableHttpResponse> response = request(url); System.out.println("Not yet subscribed."); Observable<String> stringResponse = response .flatMap(resp -> resp.getContent() .map(bytes -> new String(bytes))) .retry(5) .cast(String.class) .map(String::trim) .cache(); System.out.println("Subscribe 1:"); System.out.println(stringResponse.toBlocking().first()); System.out.println("Subscribe 2:"); System.out.println(stringResponse.toBlocking().first()); ...

Get Learning Reactive Programming with Java 8 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.