暂停协程的执行等待回调

Suspend Coroutines's execution to wait for callback

最近,我将协程应用到我的项目中,一切似乎都很好,但今天我遇到了一个问题[使用协程 + Retrofit 将 file/image 上传到服务器][1] coroutine + Retrofit 上传文件貌似没有解决方案,只能用callback来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
            }

我的问题是:如何暂停协程的执行以等待改造的回调?

谢谢兄弟。 [1]:

您可以使用 suspendCoroutine or 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 的实现。