24

是否可以使用 RxJava/RxAndroid 和 Retrofit 执行定期 http 请求以每 x 秒更新一次数据?

目前我正在使用每 x 秒触发一次的 IntentService 和 Recursive Handler/Runnable。我想知道我是否可以删除所有这些并让 RxJava 处理请求。

final RestClient client = new RestClient();
final ApiService service = client.getApiService();

public interface ApiService {
    @GET("/athletes")
    public Observable<List<Athlete>> getAthletes();
}

service.getAthletes()
.retry(3)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Athlete>>() {
    @Override
    public void call(List<Athlete> athletes) {
        // Handle Success
    }
}, new Action1<Throwable>() {
    @Override
    public void call(Throwable throwable) {
        // Handle Error
    }
});

编辑

完成后,我最终得到了以下代码。欢迎任何更新。

final Scheduler scheduler = Schedulers.from(Executors.newSingleThreadExecutor());

obs = Observable.interval(30, TimeUnit.SECONDS, scheduler)
            .flatMap(tick -> service.getAthletes(1, 0l))
            // Performed on service.getAthletes() observable
            .subscribeOn(scheduler)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(err -> Log.d("APP", "Error retrieving athletes: " + err.toString()))
            .retry()
            .flatMap(Observable::from)
            .filter(athlete -> {
                // Process Athlete here in the filter
                // Return true to always send messages but could filter them out too
                return true;
            });

public static void startUpdates() {
    if (sub != null) {
        sub = obs.subscribe(athlete -> {
            Log.d("APP", "Done updating athletes! ");
        });
    }
}

public static void stopUpdates() {
    sub.unsubscribe();
    sub = null;
}
4

1 回答 1

29

使用Observable.interval和 来防止在service.getAthletes()单个线程上订阅重叠请求:SchedulerflatMap

Scheduler scheduler = Schedulers.from(Executors.newSingleThreadExecutor());
Observable.interval(x, TimeUnit.SECONDS)
.flatMap(n -> 
    service.getAthletes()
        .retry(3)
        .subscribeOn(scheduler))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Athlete>>() {
        @Override
        public void call(List<Athlete> athletes) {
            // Handle Success
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            // Handle Error
        }
    });
于 2015-08-02T03:32:34.940 回答