我有以下简单的数据库:
NameList.kt
@Entity(tableName = "name_list")
data class NameList(
@PrimaryKey(autoGenerate = true)
var id: Long = 0L,
@ColumnInfo(name = "name")
var name: String = "")
NameListDao.kt
@Dao
interface NameListDao{
@Insert
fun insert(nameList: NameList)
@Update
fun update(nameList: NameList)
@Query("SELECT * FROM name_list ORDER BY id DESC")
fun getAll(): LiveData<List<NameList>>
}
NameListRepository.kt
class NameListRepository(private val nameListDao: NameListDao){
val allNames: LiveData<List<NameList>> = nameListDao.getAll()
}
MyViewModel.kt
class MyViewModel(app: Application): AndroidViewModel(app){
private val nameListDao = NameListDatabase.getInstance(app).nameListDao
private val repository: nameListRepository = nameListRepository(nameListDao)
private val allNames: LiveData <List<NameList>> = repository.allNames
...
}
目前,我只想获取和处理该非空数据库的最后一个条目(NameListDao
中没有更改/添加方法。
在一个片段中,很容易获得,例如使用TextView
方法(通过数据绑定在observe
中显示)最后一个数据库条目:
viewModel.allNames.observe(this, Observer<List<NameList?>> {
nameList -> binding.textView.text = nameList[nameList.lastIndex]!!.name
})
据我发现,在ViewModel
中,需要使用Transformations.map
或Transformations.switchMap
来处理LiveData
。为了获得数据库的最后一个条目并将其传递给方法doSomethingWithName()
,我尝试了以下两种(四种)方法与“转换”一起使用(均无效)。但是,在所有情况下,传递的参数显然为空。 (我也通过[0]
尝试了第一个条目,但我得到了相同的结果)
class MyViewModel(app: Application): AndroidViewModel(app){
private val nameListDao = NameListDatabase.getInstance(app).nameListDao
private val repository: nameListRepository = nameListRepository(nameListDao)
private val allNames: LiveData <List<NameList>> = repository.allNames
private var _lastName = ""
init{
Transformations.map(allNames, ::getLastName1) //first try
//Transformations.switchMap(allNames, ::getLastName2) //second try
doSomethingWithName(_lastName) //commented when executed in getLastName()
}
private fun doSomethingWithName(name: String){ ... }
private fun getLastName1(nameList: List<NameList>){
val names: MutableList<String> = ArrayList()
nameList.forEach { names.add(it.name) }
val lastName = names[names.lastIndex]
//doSomethingWithName(lastName) //third try
_lastName = lastName
}
private fun getLastName2(nameList: List<NameList>): LiveData<NameList>{
val liveData: MutableLiveData<NameList> = MutableLiveData(nameList[nameList.lastIndex])
val lastName = liveData.value!!.name
//doSomethingWithName(lastName) //fourth try
_lastName = lastName
return liveData
}
}
我在这里想念什么?
如果要获取列表中的最后一个值,请考虑列表也可能为空...