Last active
January 25, 2020 05:00
-
-
Save vamjakuldip/08f676af58dc590ed28be96d658472c0 to your computer and use it in GitHub Desktop.
Rx Java Retry Api Extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vk.android.extension | |
import com.vk.android.utils.Const | |
import io.reactivex.Observable | |
import io.reactivex.functions.BiFunction | |
import retrofit2.HttpException | |
import java.io.IOException | |
import java.io.InterruptedIOException | |
import java.net.SocketTimeoutException | |
import java.util.concurrent.TimeUnit | |
fun Observable<Throwable>.retryWhenError(): Observable<Any> { | |
return this.flatMap { error -> | |
if (error is IOException) { | |
return@flatMap Observable.timer(3, TimeUnit.SECONDS) | |
} else if (error is HttpException) { | |
if (error.code() == Const.HttpErrorCode.HTTP_BAD_GATEWAY) { | |
return@flatMap Observable.timer(5, TimeUnit.SECONDS) | |
} | |
} | |
return@flatMap Observable.error<Any>(error) | |
} | |
} | |
fun Observable<Throwable>.retryWithCountAndDelay(maxRetryCount: Int, delay: Long, unit: TimeUnit): Observable<Long> { | |
return this.zipWith(Observable.range(1, maxRetryCount), BiFunction { _: Throwable?, retryCount: Int -> retryCount }) | |
.flatMap { retryCount -> Observable.timer(Math.pow(delay.toDouble(), retryCount.toDouble()).toLong(), unit) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment