Suspend Coroutines#39;s execution to wait for callback(暂停执行协程以等待回调)
本文介绍了暂停执行协程以等待回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近,我在我的项目中应用了Cooutine,看起来一切都很好,但今天我遇到了一个问题[使用Coroutine+Retrofit将文件/图像上传到服务器][1] Cooutine+Retrofit上传文件似乎没有解决方案,所以必须使用回调进行改造。
//Api interface
interface UploadFileApiKotlin {
@Multipart
@POST("/uploadFileApi")
fun uploadFiles(
@Part listUri: List<MultipartBody.Part>
): Call<Response<List<FileResponse>?>>
}
//ViewModel class
serviceScope.launch {
//Insert into db
repository.insertNewExtAct()
//Send data into server.
val call = RequestHelper.getUpLoadFilesKotlinRequest().uploadFiles(partList)
call.enqueue(object : Callback<Response<List<FileResponse>?>> {
override fun onResponse(
call: Call<Response<List<FileResponse>?>>,
response: Response<Response<List<FileResponse>?>>
) {
TODO("Not yet implemented")
}
override fun onFailure(
call: Call<Response<List<FileResponse>?>>,
t: Throwable
) {
TODO("Not yet implemented")
}
})
//Wait for response from server and do logic
}
我的问题是:如何挂起协程的执行以等待Retrofit的回调?
谢谢你兄弟。 [1]:Upload file/image into server using Coroutine + Retrofit
推荐答案
您可以使用suspendCoroutine
或suspendCancellableCoroutine
处理回调:
serviceScope.launch {
//Insert into db
repository.insertNewExtAct()
//Send data into server.
uploadFile()
//Wait for response from server and do logic
}
suspend fun uploadFile() = suspendCoroutine<Response<List<FileResponse>?>> { continuation ->
val call = RequestHelper.getUpLoadFilesKotlinRequest().uploadFiles(partList)
call.enqueue(object : Callback<Response<List<FileResponse>?>> {
override fun onResponse(
call: Call<Response<List<FileResponse>?>>,
response: Response<Response<List<FileResponse>?>>
) {
// Resume coroutine with a value provided by the callback
continuation.resumeWith(response.data)
}
override fun onFailure(
call: Call<Response<List<FileResponse>?>>,
t: Throwable
) {
continuation.resumeWithException(t)
}
})
}
suspendCoroutine
挂起它执行的协程,直到我们决定通过调用适当的方法继续-Continuation.resume...
。suspendCoroutine
主要用于我们有一些带有回调的旧代码。
还有suspendCancellableCoroutine
生成器函数,它的行为类似于suspendCoroutine
,但有额外的功能-提供CancellableContinuation
对块的实现。
这篇关于暂停执行协程以等待回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:暂停执行协程以等待回调


基础教程推荐
猜你喜欢
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01