【发布时间】: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