使用RxJava和Retrofit的周期性HTTP请求



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

目前我正在使用IntentService和递归处理器/Runnable,每x秒触发一次。我想知道我是否可以删除所有这些,让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;
}

使用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
        }
    });

相关内容

  • 没有找到相关文章

最新更新