首页 > 解决方案 > 有没有办法将 var toyList 设计为 LiveData> 在 ViewModel 中?

问题描述

以下代码来自项目

作者在 MainViewModel 中var toyList设计。LiveData<List<ToyEntry>>?

我认为如果我设计var toyList成这样会更好,我LiveData<List<ToyEntry>>该怎么做?

class MainViewModel(application: Application) : AndroidViewModel(application) {  
    var toyList: LiveData<List<ToyEntry>>? = null
        get() {
            return field ?: mRepo.toyList.also { field = it }
        }
    ...
}


class ToyRepository private constructor(private val mDatabase: ToyDatabase, private val mExecutors: AppExecutors) {
    val toyList: LiveData<List<ToyEntry>>
        get() = mDatabase.toyDao().allToys
    ...
}



interface ToyDao {
    @get:Query("SELECT * FROM toys")
    val allToys: LiveData<List<ToyEntry>>
    ...
}

标签: androidandroid-jetpack

解决方案


如果您想通过不可为空的 LiveData 更改可空的 LiveData,使用相同的方法,观察另一个 LiveData,那么您可以使用转换:

val toyList: LiveData<List<ToyEntry>> = Transformations.map(mRepo.toyList) {
    it 
}

推荐阅读