2017-06-18 76 views
1

我想緩存retrofit2 api響應observable的最佳方法是與behaviorSubject。這會發出最後發送的項目。所以我試圖做一個函數,將採取一個布爾緩存參數,以瞭解是否應該從緩存或retrofit2調用中檢索響應。 retrofit2調用只是返回一個observable。但是讓我們看看我想要什麼:Rxjava2 - 如何緩存Observable

下面是函數之前,我實現了高速緩存,它只是簡單地做了一個retrofit2調用get訂閱了它在其他地方一個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 ? 

       } 
      }` 

回答

2

我建議你只是緩存這樣的響應(列表):

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