使用RxJava和改造的定期HTTP请求 [英] Periodic HTTP Requests Using RxJava and Retrofit

查看:89
本文介绍了使用RxJava和改造的定期HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to use RxJava/RxAndroid and Retrofit to perform periodic http requests to update data every x seconds?

目前,我正在使用每x秒触发一次的IntentService和递归处理程序/可运行对象.我想知道是否可以删除所有内容,让RxJava代替处理请求.

Currently I am using an IntentService and Recursive Handler/Runnable that fires every x seconds. I'd like to know if I could remove all that and let RxJava handle the requests instead.

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

编辑

完成所有操作后,我得到了以下代码.欢迎任何更新.

After all is done I ended up with the following code. Any updates are welcome.

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()的重叠请求在flatMap中的单个线程Scheduler上进行订阅:

Use Observable.interval and to prevent overlapping requests from service.getAthletes() subscribe on a single threaded Scheduler within the flatMap:

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

这篇关于使用RxJava和改造的定期HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆