Skip to content Skip to sidebar Skip to footer

How To Retry Api Call In Retrofit Interface With Coroutines Enabled

I have a use case whenever generic error like internet lost or unknown error occurs in API call need to show error UI with retry button. when user press retry previously failed API

Solution 1:

You can handle the retry by saving the action outside of the Coroutine job e. g. adding a dispatch on a button.

Here is simple example, but not completed:

classViewModel{

    val context = CoroutineScope(Dispatchers.Main)
    var dispatchRetry: (() -> Unit)? = nullfuncreateTodo(requestData: TodoRequest) {
        context.launch() {
            try {
                todoService.createTodo(requestData)
            } catch (t: Throwable) {
                dispatchRetry = { todoService.createTodo(requestData) }
            }
        }
    }

    funretry() {
        dispatchRetry?.invoke()
    }
}

Solution 2:

use repositories and view model to get response through live data using coroutines and then in your activity user observers to get date this is the best way to use coroutines also best practice for MVVM

Post a Comment for "How To Retry Api Call In Retrofit Interface With Coroutines Enabled"