4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rxでエラー発生時にX秒後にN回リトライする

4
Posted at

Rxでの処理内で何かしらのエラーが発生した場合に一定時間待機してから一定回数リトライし、それでもエラーの場合はエラーを流すといった処理をします。

毎回書き方を忘れてしまうので下記に残します。

下記のretryWhenError()メソッドをrxのretryWhenの引数にいれればOKです。

private fun retryWhenError(): Function<Observable<out Throwable>, Observable<Any>> {
    return Function { observable ->
        observable.zipWith(Observable.range(0, N + 1),
                BiFunction<Throwable, Int, Pair<Throwable, Int>> { throwable, integer ->
                    Pair(throwable, integer)
                })
                .flatMap<Any> { throwableIntegerPair ->
                    if (throwableIntegerPair.second < N) {
                        Observable.timer(X, TimeUnit.SECONDS)
                    } else {
                        Observable.error(throwableIntegerPair.first)
                    }
                }
    }
}

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?