Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2056
粉色の甜心
粉色の甜心 2021-01-30 23:09

I am using Retrofit 2.6.0 with coroutines for my web service call. I am getting the API response properly with all response codes (success & error cases). My Issue is when I

7条回答
  •  执念已碎
    2021-01-30 23:34

    You can just add a CoroutineExceptionHandler to handle the error for you:

    In your ViewModel:

    val coroutineExceptionHandler = CoroutineExceptionHandler{_, t -> {
      t.printStackTrace()
      showErrorOrSomething()
    }}
    
    viewModelScope.launch(Dispatchers.IO + coroutineExceptionHandler) {
       val apiResponse = ApiConnectionBridge.getHomeUiDetails(SharedPrefUtils.getAuthToken(context))
            if (apiResponse.isSuccessful) {
               // success case
            } else {
                // error case
            }
    }
    

提交回复
热议问题