通过协程创建两个序列 http 请求。第二个请求必须在第一个完成时等待

Create two sequence http request by coroutine. Second request must wait when finish first

Android 工作室 3.5 在我的项目中,我使用了 retrofit 和 kotlin。 我想通过 Kotlin 协程进行下一步:

  1. 通过改造启动第一个 http 请求。
  2. 仅在成功完成后才通过改造开始第二个 http 请求。
  3. 如果第一个请求失败则不启动第二个请求。

Kotlin 协程可以做到这一点吗?

谢谢。

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

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()
      }
    }

完成!

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