【问题标题】:Upload file/image into server using Coroutine + Retrofit使用 Coroutine + Retrofit 将文件/图像上传到服务器
【发布时间】:2022-01-18 11:31:22
【问题描述】:

我是新的协程我尝试将文件上传到服务器(使用改造 2.9.0)但我没有得到响应。 以下是代码行

private suspend fun uploadFile(inputFiles: List<String>,channel:Channel<Any>): List<FileResponse>? {
        val partList = buildFilePart(inputFiles)
        QLog.d(TAG,"uploadFile going 1")
        val response = RequestHelper.getUpLoadFilesKotlinRequest().uploadFiles(partList)
        QLog.d(TAG,"uploadFile going 2")
        return response.body()
}
interface UploadFileApiKotlin {
    @Multipart
    @POST("/uploadFile")
    suspend fun uploadFiles(
        @Part listUri: List<MultipartBody.Part>
    ): Response<List<FileResponse>?>
}

查看logcat后,只看到一行代码:

上传文件 1

没有日志行:uploadFile going 2

协程似乎在以下行被暂停:val response = RequestHelper.getUpLoadFilesKotlinRequest().uploadFiles(partList)

你能帮我解决这个问题吗? 提前致谢

【问题讨论】:

  • 此时无法暂停协程,bcz uploadFiles() 没有用suspend 关键字标记。尝试用suspend关键字标记它并返回List&lt;FileResponse&gt;?

标签: android retrofit2 kotlin-coroutines


【解决方案1】:

我发布了another question,终于我自己得到了答案

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)
        }
    })
}

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 2016-06-06
    • 2023-03-12
    • 2019-08-02
    • 2016-10-15
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多