Alexei
Alexei

Reputation: 15726

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

Upvotes: 2

Views: 2616

Answers (1)

apksherlock
apksherlock

Reputation: 8371

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. Otherwise your responses should be Deferred<Response<FirstResponseObject>> and the requests api.getFirstRequest().await()

Upvotes: 5

Related Questions