取消从 ViewModel 协程作业启动的 Retrofit 请求

Cancel Retrofit request started from ViewModel coroutine job

我希望我的应用程序用户能够取消文件上传。

我在 ViewModel 中的协程上传作业如下所示

private var uploadImageJob: Job? = null
private val _uploadResult = MutableLiveData<Result<Image>>()
val uploadResult: LiveData<Result<Image>>
    get() = _uploadResult

fun uploadImage(filePath: String, listener: ProgressRequestBody.UploadCallbacks) {
    //...
    uploadImageJob = viewModelScope.launch {
        _uploadResult.value = withContext(Dispatchers.IO) {
            repository.uploadImage(filePart)
        }
    }
}

fun cancelImageUpload() {
    uploadImageJob?.cancel()
}

然后在存储库中 Retrofit 2 请求是这样处理的

suspend fun uploadImage(file: MultipartBody.Part): Result<Image> {
    return try {
        val response = webservice.uploadImage(file).awaitResponse()
        if (response.isSuccessful) {
            Result.Success(response.body()!!)
        } else {
            Result.Error(response.message(), null)
        }
    } catch (e: Exception) {
        Result.Error(e.message.orEmpty(), e)
    }
}

cancelImageUpload() 它调用时,作业被取消并且异常被捕获在存储库中,但结果不会分配给 uploadResult.value

有什么想法可以使这项工作成功吗?

PS: 有一个类似的问题 但它建议使用 coroutines call adapter 现在已经被贬低了。

通过像这样 withContext 向上移动一级

终于成功了
uploadImageJob = viewModelScope.launch {
    withContext(Dispatchers.IO) {
        _uploadResult.postValue(repository.uploadImage(filePart))
    }
}