有没有办法在 ViewModel 中将 var toyList 设计为 LiveData<List<ToyEntry>>?

Is there a way to design var toyList as LiveData<List<ToyEntry>> in ViewModel?

以下代码来自project.

作者在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>>
    ...
}

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

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