简体   繁体   English

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

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

Android studio 3.5 In my project I use retrofit and kotlin. Android studio 3.5 在我的项目中,我使用 retrofit 和 kotlin。 I want to the next steps by Kotlin coroutine:我想通过 Kotlin 协程进行下一步:

  1. Start first http request by retrofit.通过 retrofit 请求首先启动 http 请求。
  2. Only after success finish then start second http request by retrofit.只有在成功完成后才开始由 retrofit 请求第二个 http 请求。
  3. If first request fail then NOT start second request.如果第一个请求失败,则不启动第二个请求。

Is it possible to do this by Kotlin coroutines? Kotlin 协程可以做到这一点吗?

Thanks.谢谢。

Yes, it's totally doable with coroutines:是的,使用协程是完全可行的:

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

Now, the call:现在,调用:

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.
}

But, you might wanna consider your exceptions:但是,您可能想考虑您的例外情况:

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

And then:接着:

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

Done!完毕!

For this approach, you must have retrofit 2.6 or above.对于这种方法,您必须具有 retrofit 2.6 或更高版本。 Otherwise your responses should be Deferred<Response<FirstResponseObject>> and the requests api.getFirstRequest().await()否则,您的响应应该是Deferred<Response<FirstResponseObject>>和请求api.getFirstRequest().await()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM