Rxjava2 - 如何缓存Observable

时间:2017-06-18 08:45:19

标签: caching rx-java retrofit2 rx-java2

我认为缓存retrofit2 api响应可观察的最佳方法是使用behaviorSubject。这将发出最后发送的项目。所以我试图创建一个函数,它将采用布尔缓存参数来知道是应该从缓存还是从retrofit2调用中检索响应。 retrofit2调用只返回一个observable。但让我们看看我想要的东西:

这是我实现缓存之前的功能,它只是简单地进行了一次retrofit2调用以获得api响应,并且有人在其他地方订阅了它:

     public Observable<List<CountryModel>> fetchCountries() {
        CountriesApi countriesService = mRetrofit.create(CountriesApi.class);
        return countriesService.getCountries();

    }`

这是我想要实现的,但很难实现行为主题来做到这一点?或者我怎样才能随意缓存响应?

public Observable<List<CountryModel>> fetchCountries(boolean cache) {
          CountriesApi countriesService = mRetrofit.create(CountriesApi.class);

                if(!cache){
                  //somehow here i need to wrap the call in a behaviorsubject incase next time they want a cache - so need to save to cache here for next time around but how ?
                return countriesService.getCountries();
              }  else{
    behaviorsubject<List<CountryModel>>.create(countriesService.getCountries())
    //this isnt right.  can you help ?

                }
            }`

1 个答案:

答案 0 :(得分:2)

我建议您只缓存响应(List),如下所示:

List<CountryModel> cachedCountries = null;

public Observable<List<CountryModel>> fetchCountries(boolean cache) {
    if(!cache || cachedCountries == null){
        CountriesApi countriesService = mRetrofit.create(CountriesApi.class);
        return countriesService
                .getCountries()
                .doOnNext(new Action1<List<CountryModel>>() {
                    @Override
                    public void call(List<CountryModel> countries) {
                        cachedCountries = countries;
                    }
                });
    } else {
        return Observable.just(cachedCountries);
    }
}