Rxjava2 - 如何缓存 Observable

Rxjava2 - how to cache Observable

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

这是我实现缓存之前的函数,它只是简单地进行了一个 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 ?

                }
            }`

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

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