是否可以使用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;
}
答案 0 :(得分:29)
使用Observable.interval
并防止来自service.getAthletes()
的{{1}}订阅Scheduler
订阅的重叠请求:
flatMap