我使用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
}
}
我不知道我在想什么。任何帮助将不胜感激。
这段代码:
viewModelScope.launch {
deepFilterLiveData = repo.applyFilter(compressedImage)
}
立即返回,因此当您第一次调用该onImageCompressed()
方法时,返回null
为deepFilterLiveData
。因为在您的UI中,您不会使用该子句?.
的null
返回值。没有协程的代码可以工作,因为在这种情况下,您有顺序代码,因此ViewModel等待存储库调用。onImageCompressed()
when
为了解决这个问题,您可以为ViewModel-UI交互保留LiveData并直接从存储库方法返回值:
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)
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句