【发布时间】:2019-09-18 20:26:43
【问题描述】:
Android 工作室 3.5 在我的项目中,我使用改造和 kotlin。 我想通过 Kotlin 协程进行下一步:
- 通过改造启动第一个 http 请求。
- 只有在成功完成后才能通过改造开始第二个 http 请求。
- 如果第一个请求失败,则不启动第二个请求。
Kotlin 协程可以做到这一点吗?
谢谢。
【问题讨论】:
标签: android retrofit2 kotlin-coroutines
Android 工作室 3.5 在我的项目中,我使用改造和 kotlin。 我想通过 Kotlin 协程进行下一步:
Kotlin 协程可以做到这一点吗?
谢谢。
【问题讨论】:
标签: android retrofit2 kotlin-coroutines
是的,使用协程完全可以做到:
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<Response<FirstResponseObject>>,请求应该是api.getFirstRequest().await()
【讨论】: