android - 通过协程创建两个序列的http请求。第二个请求必须在第一个完成时等待
问题描述
Android studio 3.5 In my project I use retrofit and kotlin. I want to the next steps by Kotlin coroutine:
- Start first http request by retrofit.
- Only after success finish then start second http request by retrofit.
- If first request fail then NOT start second request.
Is it possible to do this by Kotlin coroutines?
Thanks.
解决方案
是的,使用协程是完全可行的:
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()
推荐阅读
- dask - 嵌套模块的 client.upload_file()
- c# - 使用 WCF 服务时出现异常
- unix - 尝试使用 echo 命令显示文件(带或不带引号)
- c# - Header 属性在 UWP CustomTextBox 中不起作用
- json - 如何解析这样的 JSON 文件?
- javascript - 继续获取错误对象 REGEXP 不是函数
- javascript - 凭证的范围应为有效区域
- php - 如何检查具有 id 值的对象数组是否不存在于 php 中的另一个对象数组中?
- python-2.7 - 调用存储过程时如何处理ibm_db python包中的错误?
- css - 即使在使用border-collapse:separate 之后,border-radius 也没有应用于行标签