Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2194
粉色の甜心
粉色の甜心 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:46

    Maybe it helps somebody: Its possible to get rid of the SocketTimeoutException in the following way: 1. Set the readTimeout of your client to a arbitrary number, here its 2s

     val client = OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS).build()
    

    2. When doing API calls always wrap them inside a coroutine timeout.

      try {
              withTimeout(1000) {
                  try {
                      val retrivedTodo = APICall()
                      emit(retrivedTodo)
                  } catch (exception: HttpException) {
                      exception.printStackTrace()
                  }
              }
          }catch (ex: CancellationException) {
            Log.e("timeout","TimeOut")
          }
    

    The main point is, that the withTimeout value is smaller than the Retrofit timeout value. This assures, that the coroutine stops being suspended BEFORE the Retrofit timeout kicks in.

    Anyway, this is produces many try/catch blocks and is probably not what the retrofit developers wanted, when including the coroutine support.

提交回复
热议问题