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
对块的实现。
这篇关于暂停执行协程以等待回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:暂停执行协程以等待回调


基础教程推荐
猜你喜欢
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01