将ViewModelScope与LiveData一起使用时出现问题

问题描述 投票:1回答:1

我在viewModelScope中使用ViewModel,它在存储库中调用挂起函数,如下所示:

视图模型

class DeepFilterViewModel(val repo: DeepFilterRepository) : ViewModel() {

var deepFilterLiveData: LiveData<Result>? = null

 fun onImageCompressed(compressedImage: File): LiveData<Result>? {
    if (deepFilterLiveData == null) {
        viewModelScope.launch {
            deepFilterLiveData =  repo.applyFilter(compressedImage)
        }

    }
    return deepFilterLiveData
 }
}

知识库

class DeepFilterRepository {

suspend fun applyFilter(compressedImage: File): LiveData<Result> {
    val mutableLiveData = MutableLiveData<Result>()
    mutableLiveData.value = Result.Loading

    withContext(Dispatchers.IO) {
        mutableLiveData.value = Result.Success("Done")

    }
    return mutableLiveData
 }
}

我正在观察片段中的LiveData,如下所示:

 viewModel.onImageCompressed(compressedImage)?.observe(this, Observer { result ->
        when (result) {

            is Result.Loading -> {
                loader.makeVisible()
            }

            is Result.Success<*> -> {
                // Process result

            }
        }
    })

问题是我从LiveData中得不到任何价值。如果我不使用如下所示的viewModelScope.launch {},那么一切正常。

class DeepFilterViewModel(val repo: DeepFilterRepository) : ViewModel() {

var deepFilterLiveData: LiveData<Result>? = null

 fun onImageCompressed(compressedImage: File): LiveData<Result>? {
    if (deepFilterLiveData == null) {
            deepFilterLiveData =  repo.applyFilter(compressedImage)
    }
    return deepFilterLiveData
 }
}

我不知道我错过了什么。任何帮助将不胜感激。

android kotlin android-livedata android-viewmodel kotlin-coroutines
1个回答
1
投票

这段代码:

viewModelScope.launch {
   deepFilterLiveData =  repo.applyFilter(compressedImage)
}

立即返回,因此当您第一次调用onImageCompressed()方法时,返回null作为deepFilterLiveData。因为在你的UI中你使用?在onImageCompressed()的null返回值上,将不会到达when子句。没有协程的代码可以工作,因为在这种情况下你有顺序代码,你的ViewModel等待存储库调用。

要解决此问题,您可以保留LiveData以进行ViewModel-UI交互,并直接从存储库方法返回值:

class DeepFilterRepository {

    suspend fun applyFilter(compressedImage: File) = withContext(Dispatchers.IO) {
        Result.Success("Done")
    }

}

而ViewModel:

class DeepFilterViewModel(val repo: DeepFilterRepository) : ViewModel() {

    private val _backingLiveData = MutableLiveData<Result>()
    val deepFilterLiveData: LiveData<Result>
       get() = _backingLiveData

    fun onImageCompressed(compressedImage: File) {
        // you could also set Loading as the initial state for _backingLiveData.value           
       _backingLiveData.value = Result.Loading
        viewModelScope.launch {
            _backingLiveData.value = repo.applyFilter(compressedImage)
        }
    }     
}
© www.soinside.com 2019 - 2024. All rights reserved.