Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava + Retrofit + polling

I have a Retrofit call and want to recall it every 30sec. To do that I use an Observable.interval(0, 30, TimeUnit.SECONDS)

Observable
    .interval(0, 30, TimeUnit.SECONDS)
    .flatMap(x -> RestApi.instance().getUsers())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(list -> {
                    // ...
               },
               error -> Timber.e(error, "can't load users"));

My problem: If the api call fails, onError is called and the subscription unsubscribes and the polling isn't working anymore :-(

To catch the api error I added a retryWhen

Observable
    .interval(0, 30, TimeUnit.SECONDS)
    .flatMap(x -> RestApi.instance().getUsers()
                         .retryWhen(errors -> errors
                             .flatMap(error -> Observable.timer(15, TimeUnit.SECONDS))))
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(list -> {
                   // ...
               },
               error -> Timber.e(error, "can't load users"));

This catches the error but I get multiple api calls over the time. Every 30sec I get a new poll signal which ends in a new api request. But if the api request fails it retries itself. So I have a new request plus all retries.

My question: How can I handle an api error without unsubscribing from the poll signal?

like image 308
Ralph Bergmann Avatar asked May 11 '16 10:05

Ralph Bergmann


1 Answers

Read how to properly use retryWhen and repeatWhen. http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/

And how to use onError operators: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/

It's really easy w Rx :) I'm not gonna give you a final solution, just play around with it and try to understand the flow here.

like image 130
rafakob Avatar answered Sep 30 '22 20:09

rafakob