【问题标题】:MutableLiveData observe method runs but doesn't update Jetpack Compose listMutableLiveData 观察方法运行但不更新 Jetpack Compose 列表
【发布时间】:2022-01-24 23:59:07
【问题描述】:

所以我浪费了好几天的时间,我的截止日期是明天

基本上,我有一个 mutableLiveData var,它是一个伴生对象,

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

观察函数被正常调用,它执行您可以看到的打印语句,

但它完全跳过了 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)
                    }
                }
            )
        }
    }

【问题讨论】:

    标签: android kotlin android-livedata android-jetpack android-jetpack-navigation


    【解决方案1】:

    在 Compose 中,您不应直接在 @Composable 内观察 LiveData,而应将其观察为 State。现在我们有了Recomposition(@Composable 函数在每次@Composable 函数中观察到的值发生变化时自动一次又一次地调用),而不是更新 UI 的回调。

    更多信息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
        }
    }
    

    【讨论】:

    • 对不起,我忘了回答,但已经解决了,非常感谢你的朋友!
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多