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 : Created and started the client.
main : About to create Observable.
[{"id":7268616,"name":"Rx.rb",...
I/O dispatcher 1 : Closing the client.
Subscribe 2:
[{"id":7268616,"name":"Rx.rb",...

Now, we can reuse our stringResponse Observable instance through our programs without making additional resource allocation and request.

At last, the requestJson() method can be implemented like this:

public Observable<Map> requestJson(String url) {
Observable<String> rawResponse = request(url)

....

return Observable.amb(fromCache(url), response);
}

Simpler and with resource auto management (the resource, a http client is created and destroyed automatically ), the method implements its own caching functionality too (we implemented it back in Chapter 5, Combinators, Conditionals, and Error Handling).

Note

All the methods, which create Observable instances, developed through the book can be found at https://github.com/meddle0x53/learning-rxjava/blob/master/src/main/java/com/packtpub/reactive/common/CreateObservable.java class contained in the source code. There is also a cache-in-files implementation for the requestJson() method that you can find there.

With this, we are able to extend RxJava, creating our own factory methods to make Observable instances dependent on arbitrary data sources.

The next section of the chapter will show how to put our own logic into the Observable chain of operators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.80.100