I am making a network using Retorfit
+ RxJava2
and I want to cache the response for 30 seconds. Any calls made after 30 seconds interval should get the latest results from server. I tried doing this using Replay
operator but it still makes a network call every time I call subscribe. I am not an expert in RxJava so maybe my understanding of using Replay
for caching like that is wrong.
public Observable<Name> getName() {
return retrofitBuilder.getName()
.subscribeOn(Schedulers.io())
.replay(30, TimeUnit.SECONDS,Schedulers.io())
.autoConnect();
}
and I am calling the above code like this:
service.getName()
.subscribe(new Consumer<Name>()
{
@Override
public void accept(Name name) throws Exception
{
Log.d("getName", "Name: " + name.toString());
}
}
, new Consumer<Throwable>()
{
@Override
public void accept(Throwable throwable) throws Exception
{
Log.d("getName", throwable.getMessage());
}
});
UPDATE: My apology if I didn't explain my question clearly. What I want is caching on a particular request instead of caching it on HttpClient
level which applies the caching strategy to all the request being made through it. In the end I would like to define different caching expiration for different request when needed. Not all my request needs caching for small duration. I was wondering if I could do just that.
Appreciate your help in this.
service.getName()
will return a newObservable
. Thatreplay
operator, and others like it, are meant to allow multicasting of various sorts on a single Observable. Most likely, you'd want to implement caching behind theservice.getName()
method, such that it will offer caching functionality regardless of how many separate Observables you create that run it. This might mean you implement caching at the Http client layer, with "Cache-Control", or some other method. – Denitadenitrate