使用RxJava和Retrofit的定期HTTP请求

时间:2015-08-02 03:03:18

标签: android retrofit rx-java rx-android

是否可以使用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;
}

1 个答案:

答案 0 :(得分:29)

使用Observable.interval并防止来自service.getAthletes()的{​​{1}}订阅Scheduler订阅的重叠请求:

flatMap