【问题标题】:Create two sequence http request by coroutine. Second request must wait when finish first通过协程创建两个序列的http请求。第二个请求必须在第一个完成时等待
【发布时间】:2019-09-18 20:26:43
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: android retrofit2 kotlin-coroutines


    【解决方案1】:

    是的,使用协程完全可以做到:

    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&lt;Response&lt;FirstResponseObject&gt;&gt;,请求应该是api.getFirstRequest().await()

    【讨论】:

    • 对我来说,使用 deferred 语法更清晰,因为您明确调用 await 并且您可以更好地控制请求。
    • 我想我不得不不同意你的观点。在新版本的 Retrofit 上,Retrofit 会为您做到这一点。无需手动操作
    • 哦,我的错,我没有看到您从延迟功能更改为暂停功能,在这种情况下,是的更好。
    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多