android 挂起协程的执行以等待回调

eqqqjvef  于 2023-06-27  发布在  Android
关注(0)|答案(1)|浏览(164)

最近,我将协程应用到我的项目中,一切似乎都很好,但今天我遇到了一个问题Upload file/image into server using Coroutine + Retrofit
似乎没有办法用协程+ 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
            }

我的问题是:我如何挂起协程的执行来等待reflect的回调?

odopli94

odopli941#

您可以使用suspendCoroutinesuspendCancellableCoroutine来处理回调(将回调转换为suspend函数):

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的实现。

相关问题