长时间运行的RxJava订阅,具有可刷新的数据

时间:2016-12-19 17:28:27

标签: android rx-java

我正在寻找为Android / RxJava中的特定数据对象设置长时间运行的数据订阅。特别是Retrofit REST调用与缓存数据配对的组合。我完成这个只是简单地用数据包装一个API调用,如果API调用是Retrofit返回一个Observable:

class OpenWeather {
    ...
    Observable<CurrentWeather> OpenWeather.getLocalWeather()
    ...
}

简单的实现将是:

public static Observable<CurrentWeather> getWeatherOnce() {
    if (currentWeather != null)
        return Observable.just(currentWeather);
    return OpenWeather.getLocalWeather()
        .map(weather -> currentWeather = weather);
}
private static CurrentWeather currentWeather;

问题是当“当前天气”更新时无法通知。在订阅之间添加长时间运行更新的可刷新数据的最简单方法是使用如下行为主题:

public class DataModel {

    public enum DataState {
        ANY,        // whatever is available, don't require absolute newest
        LATEST,     // needs to be the latest and anything new
    }

    private final static BehaviorSubject<CurrentWeather> currentWeatherSubject = BehaviorSubject.create();

    public static Observable<CurrentWeather> getCurrentWeather(DataState state) {
        synchronized (currentWeatherSubject) {
            if (state == DataState.LATEST || currentWeatherSubject.getValue() == null) {
                OpenWeather.getLocalWeather()
                    .subscribeOn(Schedulers.io())
                    .toSingle()
                    .subscribe(new SingleSubscriber<CurrentWeather>() {
                        @Override
                        public void onSuccess(CurrentWeather currentWeather) {
                            currentWeatherSubject.onNext(currentWeather);
                        }

                        @Override
                        public void onError(Throwable error) {
                            // ?? currentWeatherSubject.onError(error);
                        }
                    });
            }
        }
        return currentWeatherSubject.asObservable();
    }
}

使用BehaviorSubject,在获取当前天气时,获取最后一个缓存条目以及发生的任何更新。思考?

所以我确定我在这里做错了,因为似乎应该有一种更简单的方式或更优雅的方式。

0 个答案:

没有答案