How to cache observable in RxJava/RxScala

248 views Asked by At

I have a REST API that calling mongodb using the reactive scala driver which based on RxScala.

In my API controllers or services layers, I need to use caching to avoid calls to mongodb using hazelcast (or any other caching tools)

All my services are async and returns only observable, any idea how I can implement the caching with observable?

2

There are 2 answers

0
Maxim Volgin On

Cache in .doOnNext(), retrieve as .myFromCacheObservable().switchIfEmpty(serviceCallOrDbOrWhatever.doOnNext(mySaveToCache))

0
Ankit Kumar On
Observable<String> stringResponse = response
.flatMap(resp -> resp.getContent()
.map(bytes -> new String(bytes)))
.retry(5)
.cast(String.class)
.map(String::trim)
.cache();  //remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers

Try this. Should help you.