How to add a timeout to detect that an Observable didn't emit for a while

前端 未结 1 1283
长情又很酷
长情又很酷 2021-02-10 12:09

My use-case is following:

I created an Observable to access a remote server to fetch some data. However there could be no response and no exception from it forever due

1条回答
  •  孤街浪徒
    2021-02-10 12:46

    You can use timeout() operator together with retryWhen():

    Observable.fromEmitter(fetchNetwork->...)
         .timeout(TIMEOUT_VALUE, TimeUnit.SECONDS)
         .retryWhen(observable -> observable.flatMap(error -> {
                    if (error instanceof TimeoutException) {
                        return Observable.just(new Object());
                    } else {
                        return Observable.error(error);
                    }
                }))
         .subscribe(handleResult)
    

    this will timeout the request after TIMEOUT_VALUE seconds, and will retry as long the request was timeout, other errors will be propagate as usual to the subscriber onError().

    0 讨论(0)
提交回复
热议问题