Android 通过协同路由创建两个序列http请求。第二个请求必须在第一次完成时等待
安卓工作室3.5 在我的项目中,我使用翻新和kotlin。 我想通过Kotlin coroutine了解以下步骤:Android 通过协同路由创建两个序列http请求。第二个请求必须在第一次完成时等待,android,retrofit2,kotlin-coroutines,Android,Retrofit2,Kotlin Coroutines,安卓工作室3.5 在我的项目中,我使用翻新和kotlin。 我想通过Kotlin coroutine了解以下步骤: 通过改造启动第一个http请求 只有在成功完成后,才能通过改造启动第二个http请求 如果第一个请求失败,则不启动第二个请求 科特林公司是否有可能做到这一点 谢谢。是的,使用协同程序完全可行: interface MyApi{ @GET suspend fun firstRequest(): Response<FirstRequestResonseObject
谢谢。是的,使用协同程序完全可行:
interface MyApi{
@GET
suspend fun firstRequest(): Response<FirstRequestResonseObject>
@GET
suspend fun secondRequest(): Response<SecondRequestResponseObject>
}
<>但是,你可能会考虑你的例外:
val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable -> throwable.printStackTrace()
}
然后:
coroutineScope.launch(coroutineExceptionHandler ){
val firstRequest = api.getFirstRequest()
if(firstRequest.isSuccessFul){
val secondRequest = api.getSecondRequest()
}
}
完成了
对于这种方法,您必须进行改装2.6或更高版本。否则您的响应应该是延迟的,而对我来说,使用延迟的请求应该是
api.getFirstRequest().await()
,因为您显式地调用await,并且您对请求有更多的控制权。我想我不同意您的观点。在新版本的改型中,改型为您实现了这一点。没有必要手动操作哦,我不好,我没有看到您从延迟功能更改为暂停功能,在这种情况下,是的,它更好。
coroutineScope.launch(coroutineExceptionHandler ){
val firstRequest = api.getFirstRequest()
if(firstRequest.isSuccessFul){
val secondRequest = api.getSecondRequest()
}
}