简体   繁体   中英

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,

and when the data is updated it calls the observe function inside the grid.

The observe function gets called fine, it does the print statements which you can see,

but it completely skips everything in the compose "items()" method.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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