简体   繁体   English

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

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

so I wasted a good couple of days on this, and my deadline's tomorrow所以我浪费了好几天的时间,我的截止日期是明天

basically, I have a mutableLiveData var which is a companion object,基本上,我有一个 mutableLiveData var,它是 object 的伴侣,

and when the data is updated it calls the observe function inside the grid.并且当数据更新时,它会在网格内调用观察 function。

The observe function gets called fine, it does the print statements which you can see,观察 function 被调用很好,它执行您可以看到的打印语句,

but it completely skips everything in the compose "items()" method.但它完全跳过了 compose "items()" 方法中的所有内容。

Can someone please help me?有人可以帮帮我吗? I could not find anything useful online...我在网上找不到任何有用的东西...

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

In Compose you shouldn't observe LiveData directly inside a @Composable, but observe it as State .在 Compose 中,您不应直接在 @Composable 内观察 LiveData,而应将其观察为State Instead of callbacks to update UI, now we have Recomposition (@Composable function getting called automatically over and over again every time an observed value in the @Composable function changes).现在我们有Recomposition (@Composable function 会在每次 @Composable function 中的观察值发生变化时自动一遍又一遍地自动调用),而不是更新 UI 的回调。

More info here更多信息在这里

Your code should look more like:您的代码应该看起来更像:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM