【问题标题】:Rxjava2 - how to cache ObservableRxjava2 - 如何缓存 Observable
【发布时间】:2017-06-18 20:12:47
【问题描述】:

我认为缓存可观察的 Retrofit2 api 响应的最佳方法是使用 behaviorSubject。这将发出最后发送的项目。所以我正在尝试制作一个函数,该函数将采用布尔缓存参数来了解是否应该从缓存或retrofit2调用中检索响应。 retrofit2 调用只返回一个 observable。但是让我们看看我想要什么:

这是我实现缓存之前的函数,它只是简单地进行了一次改造2 调用以获取 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 ?

                }
            }`

【问题讨论】:

    标签: caching rx-java retrofit2 rx-java2


    【解决方案1】:

    我建议您像这样缓存响应(列表):

    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);
        }
    }
    

    【讨论】:

    • 如果您同时有多个订阅者,它将不起作用。因为缓存逻辑将在您每次调用方法时运行,而不是在您订阅 observable 时运行。您应该共享 observable,或者应该将方法主体放在 Observable.deferred 块中。
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2018-12-21
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多