[英]Livedata don't update compose state when list item property has changed
My problem is that live data observer is triggered Observer<T> { state.value = it }
with the correct data but compose doesn't kick on recompose.我的问题是实时数据观察器被触发Observer<T> { state.value = it }
使用正确的数据但撰写不会启动重组。 Only when I add an item all changes are propagated.只有当我添加一个项目时,所有更改才会传播。 There must some checking on the list itself if it has changed.如果列表已更改,则必须对列表本身进行一些检查。 I guess it doens't compare list items.我想它不会比较列表项。
@Composable
fun <R, T : R> LiveData<T>.observeAsState(initial: R): State<R> {
val lifecycleOwner = LifecycleOwnerAmbient.current
val state = remember { mutableStateOf(initial) }
onCommit(this, lifecycleOwner) {
val observer = Observer<T> { state.value = it }
observe(lifecycleOwner, observer)
onDispose { removeObserver(observer) }
}
return state
}
val items: List<TrackedActivityWithMetric> by vm.activities.observeAsState(mutableListOf())
LazyColumnForIndexed(
items = items,
Modifier.padding(8.dp)
) { index, item ->
....
MetricBlock(item.past[1], item.activity.id )
}
So behind the scenes there must be some kind hash comparing mechanism preventing rendering same item twice (More elabored answer wanted).所以在幕后必须有某种 hash 比较机制防止渲染相同的项目两次(需要更详细的答案)。 The incorrect rendering was caused by property which was not in TrackedActivityWithMetric
data class constructor.不正确的呈现是由不在TrackedActivityWithMetric
数据 class 构造函数中的属性引起的。
Jetpack Compose does not work well with MutableList, you need to use a List and do something like this: Jetpack Compose 不能很好地与 MutableList 配合使用,您需要使用 List 并执行如下操作:
var myList: List<MyItem> by mutableStateOf(listOf())
private set
for adding an item:添加项目:
fun addItem(item: MyItem) {
myList = myList + listOf(myItem)
}
for editing an item:用于编辑项目:
fun editItem(item: MyItem) {
val index = myList.indexOf(myItem)
myList = myList.toMutableList().also {
it[index] = myItem
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.