Book Image

Learning Reactive Programming with Java 8

By : Nickolay Tzvetinov
Book Image

Learning Reactive Programming with Java 8

By: Nickolay Tzvetinov

Overview of this book

Table of Contents (15 chapters)
Learning Reactive Programming with Java 8
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 :...