在LiveData中使用viewModelScope的问题

时间:2019-05-01 07:15:29

标签: android kotlin android-livedata android-viewmodel kotlin-coroutines

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

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

我不知道我在想什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

此代码:

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

立即返回,因此当您首次调用onImageCompressed()方法时,将返回null作为deepFilterLiveData。因为在您的UI中使用?。在onImageCompressed()的空返回值上,将不会到达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)
        }
    }     
}