Reputation: 15726
Android studio 3.5 In my project I use retrofit and kotlin. I want to the next steps by Kotlin coroutine:
Is it possible to do this by Kotlin coroutines?
Thanks.
Upvotes: 2
Views: 2616
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