首页 > 解决方案 > 通过协程创建两个序列的http请求。第二个请求必须在第一个完成时等待

问题描述

Android studio 3.5 In my project I use retrofit and kotlin. I want to the next steps by Kotlin coroutine:

  1. Start first http request by retrofit.
  2. Only after success finish then start second http request by retrofit.
  3. If first request fail then NOT start second request.

Is it possible to do this by Kotlin coroutines?

Thanks.

标签: androidretrofit2kotlin-coroutines

解决方案


是的,使用协程是完全可行的:

interface MyApi{
    @GET
    suspend fun firstRequest(): Response<FirstRequestResonseObject>
    @GET
    suspend fun secondRequest(): Response<SecondRequestResponseObject>
}

现在,调用:

coroutineScope.launch{
  //Start first http request by retrofit.
  val firstRequest = api.getFirstRequest()
  if(firstRequest.isSuccessFul){
    //Only after success finish then start second http request by retrofit.
    val secondRequest = api.getSecondRequest()
  }
 //If first request fail then NOT start second request.
}

但是,您可能想考虑您的例外情况:

val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable -> throwable.printStackTrace()
}

接着:

coroutineScope.launch(coroutineExceptionHandler ){
      val firstRequest = api.getFirstRequest()
      if(firstRequest.isSuccessFul){
        val secondRequest = api.getSecondRequest()
      }
    }

完毕!

对于这种方法,您必须改造 2.6 或更高版本。否则你的回应应该是Deferred<Response<FirstResponseObject>>和请求api.getFirstRequest().await()


推荐阅读