MutableLiveData 观察方法运行但不更新 Jetpack Compose 列表

MutableLiveData observe method runs but doesn't update Jetpack Compose list

所以我在这上面浪费了好几天,我的截止日期是明天

基本上,我有一个 mutableLiveData 变量,它是一个伴随对象,

当数据更新时,它会调用网格内的观察函数。

observe 函数被调用得很好,它执行您可以看到的打印语句,

但它完全跳过了编写“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. Instead of callbacks to update UI, now we have Recomposition(每次 @Composable 函数中的观察值发生变化时,@Composable 函数都会被自动一遍又一遍地调用).

更多信息here

您的代码应该更像:

@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
    }
}