有没有一种方法可以将var toyList设计为ViewModel中的LiveData <List <ToyEntry >>?

问题描述

以下代码来自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 
}