![](/img/trans.png)
[英]Maintaining List item state when List item property changed in its DetailsActivity?
[英]Livedata don't update compose state when list item property has changed
我的問題是實時數據觀察器被觸發Observer<T> { state.value = it }
使用正確的數據但撰寫不會啟動重組。 只有當我添加一個項目時,所有更改才會傳播。 如果列表已更改,則必須對列表本身進行一些檢查。 我想它不會比較列表項。
@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 )
}
所以在幕后必須有某種 hash 比較機制防止渲染相同的項目兩次(需要更詳細的答案)。 不正確的呈現是由不在TrackedActivityWithMetric
數據 class 構造函數中的屬性引起的。
Jetpack Compose 不能很好地與 MutableList 配合使用,您需要使用 List 並執行如下操作:
var myList: List<MyItem> by mutableStateOf(listOf())
private set
添加項目:
fun addItem(item: MyItem) {
myList = myList + listOf(myItem)
}
用於編輯項目:
fun editItem(item: MyItem) {
val index = myList.indexOf(myItem)
myList = myList.toMutableList().also {
it[index] = myItem
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.