Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-retry API calls for Network exception #17

Merged
merged 1 commit into from
Jan 14, 2024

Conversation

shahzadansari
Copy link
Owner

  • Use Flow's catch { } to catch exceptions instead of try { } catch { } block.
  • Retry failed API calls if they get a Network exception.
  • Emits Loading state immediately when Flow starts emitting value.
  • Flows on Dispatchers.IO by default.

Uses Flow's retryWhen { } to retry API call 3 times if it had gotten a Network exception.

fun <T> Flow<DataState<T>>.safeDataStateFlow(coroutineContext: CoroutineContext = Dispatchers.IO, autoRetry: Boolean = true): Flow<DataState<T>> =
    retryWhen { cause, attempt -> autoRetry && canRetry(cause, attempt) }
        .catch { (it as? Exception)?.toApiException()?.let { exception -> emit(DataState.Error(exception)) } }
        .flowOn(coroutineContext)
        .onStart { emit(DataState.Loading()) }

Current implementation retries 3 times and only if it was a Network exception.

private suspend fun canRetry(cause: Throwable, attempt: Long, retries: Int = 3, delayBetweenRetries: Long = 500): Boolean {
    val isNetworkException = (cause as? Exception)?.toApiException() == ApiException.Network
    val canRetry = isNetworkException && attempt < retries
    return if (canRetry) {
        delay(delayBetweenRetries)
        true
    } else {
        false
    }
}

@shahzadansari shahzadansari merged commit b87f5e2 into main Jan 14, 2024
@shahzadansari shahzadansari self-assigned this Mar 14, 2024
@shahzadansari shahzadansari deleted the auto-retry-failed-network-calls branch March 16, 2024 17:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant