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());
The cache()
operator called at the end of the stringResponse
chain will cache the response represented by a string
for all the following subscribers
. So, the output this time will be:
Not yet subscribed. Subscribe 1: main :...