Periodic HTTP Requests Using RxJava and Retrofit

前端 未结 1 566
太阳男子
太阳男子 2020-12-24 02:31

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

Currently I am using an IntentService and Recu

相关标签:
1条回答
  • 2020-12-24 03:08

    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
            }
        });
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题