【问题标题】:Rxjava2 how to return cached values if time does't come out如果时间不出来,Rxjava2如何返回缓存值
【发布时间】:2017-12-08 21:35:38
【问题描述】:

我有一个问题。我有简单的 Observable。

public interface CitiesApi {
    @GET("location/cities")
    Observable<List<City>> getCities(@Query("country") String countryId);
}

我还有 class(manager),它保存来自这个 observable 的数据并将其交给活动或演示者。

public class Manager {

    @Inject
    CitiesApi mCitiesApi;

    private Date mDate;
    private List<City> mCities;

    public Observable<List<City>> getObservable() {
        return mCitiesApi.getCities("123");
    }      
}

问题:当我订阅这个 observable 时,

当前时间 - 上次订阅时间

我想用旧数据调用 onNext。但如果时差 > 10 我想从网上下载数据(返回原始可观察数据)。我不想使用改造缓存,因为我可以手动更改此列表。

【问题讨论】:

  • 您甚至可以在调用 Observable 之前完成它。您对缓存数据进行测试,不到 10 分钟,您只需返回数据,否则您进行网络调用并更新缓存数据和时间
  • 你能告诉我,它的可观察性如何?

标签: android rx-java2


【解决方案1】:

你的 Observable 必须是这样的:

public Observable<List<City>> getObservable() {

if (cacheTime > 10){ //If cached data time is greater than 10min, you make your network call.
        return mCitiesApi.getCities("123");
} else{
    return Observable.just(getChachedData("123")) //Where getChachedData is a method that return a list of your cached data. 
}
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 2015-06-30
    • 2020-04-17
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2019-02-15
    相关资源
    最近更新 更多