简体   繁体   中英

How to force jetpack compose to recompose?

Say that, I'm building a custom compose layout and populating that list as below

val list = remember { dataList.toMutableStateList()}
MyCustomLayout{
    
   list.forEach { item ->
        key(item){
             listItemCompose( data = item,
                              onChange = { index1,index2 -> Collections.swap(list, index1,index2)})
   }
}

This code is working fine and the screen gets recomposed whenever onChange lambda function is called, but when it comes to any small change in any item's property, it does not recompose, to elaborate that let's change the above lambda functions to do the following

{index1,index2 -> list[index1].propertyName = true} 

Having that lambda changing list item's property won't trigger the screen to recompose. I don't know whether this is a bug in jetpack compose or I'm just following the wrong approach to tackle this issue and I would like to know the right way to do it from Android Developers Team. That's what makes me ask if there is a way to force-recomposing the whole screen.

call this

currentComposer.composition.recompose()

You can't force a composable function to recompose, this is all handled by the compose framework itself, there are optimizations to determine when something has changed that would invalidate the composable and to trigger a recomposition, of only those elements that are affected by the change.

The problem with your approach is that you are not using immutable classes to represent your state. If your state changes, instead of mutating some deep variable in your state class you should create a new instance of your state class (using Kotin's data class ), that way (by virtue of using the equals in the class that gets autogenerated) the composable will be notified of a state change and trigger a recomposition.

Compose works best when you use UDF (Unidirectional Data Flow) and immutable classes to represent the state.

This is no different than, say, using a LiveData<List<Foo>> from the view system and mutating the Foo s in the list, the observable for this LiveData would not be notified, you would have to assign a new list to the LiveData object. The same principle applies to compose state.

you can recreate an entire composition using this

val key = remember { mutableStateOf("yourKey")}
key(key.value) {
 YourComposableFun()
}

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