android - 取消从 ViewModel 协程作业开始的改造请求

标签 android kotlin retrofit2 viewmodel coroutine

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

我在 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:有一个类似的问题Cancel file upload (retrofit) started from coroutine kotlin android但它建议使用 coroutines call adapter现在已被贬低。

最佳答案

终于设法通过移动 withContext 使其工作像这样上一级

uploadImageJob = viewModelScope.launch {
    withContext(Dispatchers.IO) {
        _uploadResult.postValue(repository.uploadImage(filePart))
    }
}

关于android - 取消从 ViewModel 协程作业开始的改造请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694176/

相关文章:

android - View 绑定(bind)出现错误 : incompatible with attribute android:visibility

json - 如何解析包含键值对的 JSON 对象?

java - 改造 - 使用相同的 key 发送动态查询

collections - Java Stream.collect 的 Kotlin 等价物是什么?

java - 使用 TestRestTemplate 和 MockRestServiceServer 时,解析异常而不是实体列表不起作用

java - 基于 RxJava 和游标的 RESTful 分页

android - Android Studio 3.4.1 中 "Profile or Debug APK..."选项消失到哪里了?

android - Dexguard:在没有 Android 应用程序的情况下加密 .so 文件

java - 我的 android 项目测试设置中缺少任何内容吗?

java - Volley API 是线程安全的吗?