Home > Net >  How to continue polling with observable interval if error occurs
How to continue polling with observable interval if error occurs

Time:07-01

I have a simple network polling function with observable intervals

private fun pollFromApi(): Observable<MyState> {
    return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
        .startWith(0L)
        .flatMap {
            api.getState().toObservable()
        }
        .map {
            // map response to MyState
        }
        .onErrorReturn {
            return@onErrorReturn MyState.Polling // if error occurred emit Polling State
        }
        .takeUntil {
            // stop polling if certain State is reached
        }
}

The problem I have is that if in the middle of polling one of the network API calls fails, the polling stops. Ideally what I want is to keep retrying until takeUntil stops the polling and if an error occurs, just ignore it and do not emit anything to observers.

I tried adding onErrorReturn but that just catches the error and stops the polling.

CodePudding user response:

You can use Observable#onErrorResumeNext operator chained to your remote (possibly failing) API call, emitting an item that does not meet your #takeUntil clause to avoid stopping processing:

private fun pollFromApi(): Observable<MyState> {
    return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
        .startWith(0L)
        .flatMap {
            api.getState().toObservable().onErrorResumeNext(ignored -> null) // or some other SENTINEL value
        }
        .map {
            // map response to MyState
        }
        .takeUntil {
            // stop polling if certain State is reached
        }
}

CodePudding user response:

As I mentioned in the comments, you'll have to do the mapping and error handling on the api call itself inside the flatMap:

private fun pollFromApi(): Observable<MyState> {
    return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
        .startWith(0L)
        .flatMap {
            api.getState().toObservable()
            .map {
                // map response to MyState
            }
            .onErrorReturn {
                return@onErrorReturn MyState.Polling // if error occurred emit Polling State
            }
        }
        .takeUntil {
            // stop polling if certain State is reached
        }
}
  • Related