[英]LazyColumn notify about modification of item
我有一个看起来像这样的可组合函数:
@Composable
fun listScreen(context: Context, owner: ViewModelStoreOwner) {
val repository = xRepository(getAppDatabase(context).xDao()
val listData by repository.readAllData.observeAsState(emptyList())
// repository.readAllData returns LiveData<List<xEntity>>
// listData is a List<xEntity>
LazyColumn(){
items(listData.size) {
Card {
Text(listData[it].name)
Text(listData[it].hoursLeft.toString())
Button(onClick = {updateInDatabase(owner, name = listData[it], hoursLeft = 12)}) {...}
}
}
}
}
fun updateInDatabase(owner: ViewModelStoreOwner, name: String, hoursLeft: Int) {
val xViewModel....
val newEntity = xEntity(name=name, hoursLeft = Int)
xViewModel.update(newEntity)
}
正如您可能猜到的那样,LazyColumn 在修改实体后不会刷新,有没有办法在每次更新实体后更新 listData?
编辑:
class xRepository(private val xDatabaseDao) {
val readAllData: LiveData<List<xEntity>> = xDatabaseDao.getallXinfo()
...
suspend fun updatePlant(x: xEntity) {
plantzDao.updateX(x)
}
}
interface xDatabaseDao {
@Query("SELECT * FROM xInfo ORDER BY id DESC")
fun getAllXInfo(): LiveData<List<xEntity>>
....
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateX(x: xEntity?)
}
实体修改:
fun updatePlantInDatabase(owner: ViewModelStoreOwner, name: String, waterAtHour: Int, selectedDays: ArrayList<Int>) {
val xViewModel: xViewModel = ViewModelProvider(owner).get(xViewModel::class.java)
val new = xEntity(name = name, waterAtHour = waterAtHour, selectedDays = selectedDays)
xViewModel.updatePlant(new)
}
我使用mutableStateOf
来包装需要重组的字段。 如
class TestColumnEntity(
val id: String,
title: String = ""
){
var title: String by mutableStateOf(title)
}
看法:
setContent {
val mData = mutableStateListOf(
TestColumnEntity("id_0").apply { title = "cnm"},
TestColumnEntity("id_1").apply { title = "cnm"},
TestColumnEntity("id_2").apply { title = "cnm"},
TestColumnEntity("id_3").apply { title = "cnm"},
TestColumnEntity("id_4").apply { title = "cnm"},
TestColumnEntity("id_5").apply { title = "cnm"},
)
Column {
Button(onClick = {
mData.add(TestColumnEntity("id_${Random.nextInt(100) + 6}").apply { title = "ccnm" })
}) {
Text(text = "add data")
}
Button(onClick = {
mData[1].title = "test_${Random.nextInt(100)}"
}) {
Text(text = "update data")
}
TestLazyColumn(data = mData, key = {index, item ->
item.id
}) {
Text(text = it.title)
}
}
}
它适用于我的测试用例
如果您想更新惰性列(比如在 jetpack compose 中重新组合),请使用副作用。 当列表更改副作用时,将列表获取功能置于副作用(启动效果或其他副作用)中,自动重组您的功能并显示更新的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.