[英]MutableLiveData observe method runs but doesn't update Jetpack Compose list
所以我浪費了好幾天的時間,我的截止日期是明天
基本上,我有一個 mutableLiveData var,它是 object 的伴侶,
並且當數據更新時,它會在網格內調用觀察 function。
觀察 function 被調用很好,它執行您可以看到的打印語句,
但它完全跳過了 compose "items()" 方法中的所有內容。
有人可以幫幫我嗎? 我在網上找不到任何有用的東西...
@ExperimentalFoundationApi
@Composable
fun ItemsGrid() {
LazyVerticalGrid(
cells = GridCells.Fixed(3),
contentPadding = PaddingValues(8.dp)
) {
mProductsByCategoryID.observe(viewLifecycleOwner,
{ products ->
println("DATA CHANGGED ${products[0].name}")
println(mProductsByCategoryID.value?.get(0)?.name)
items(products) {
println("INSIDE ITEMS for products ${it.name}") // never gets inside of here except for the first time the view loads
DemoCards(demo = it)
}
}
)
}
}
在 Compose 中,您不應直接在 @Composable 內觀察 LiveData,而應將其觀察為State 。 現在我們有Recomposition (@Composable function 會在每次 @Composable function 中的觀察值發生變化時自動一遍又一遍地自動調用),而不是更新 UI 的回調。
更多信息在這里
您的代碼應該看起來更像:
@Composable
fun ItemsGrid() {
val productsByCategory = mProductsByCategoryID.observeAsState()
LazyVerticalGrid(
cells = GridCells.Fixed(3),
contentPadding = PaddingValues(8.dp)
) {
//here goes code that does what your callback was doing before.
//when val productsByCategory.value changes, ItemsGrid()
//gets recomposed (called again) and this code will execute
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.