繁体   English   中英

如何强制jetpack compose重组?

[英]How to force jetpack compose to recompose?

这么说,我正在构建一个自定义撰写布局并填充该列表,如下所示

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} 

拥有 lambda 更改列表项的属性不会触发屏幕重新组合。 我不知道这是否是 jetpack compose 中的错误,或者我只是采用了错误的方法来解决这个问题,我想知道 Android 开发团队的正确方法。 这就是让我问是否有办法强制重组整个屏幕的原因。

叫这个

currentComposer.composition.recompose()

您不能强制可组合的 function 进行重组,这一切都由 compose 框架本身处理,有一些优化可以确定何时发生某些更改会使可组合无效并触发重组,只有那些受改变。

您的方法的问题是您没有使用不可变类来表示您的 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将通知 state 更改并触发重组。

当您使用 UDF(单向数据流)和不可变类来表示 state 时,Compose 效果最佳。

这与使用视图系统中的LiveData<List<Foo>>并改变列表中的Foo没有什么不同,不会通知此LiveData的可观察对象,您必须将新列表分配给实时数据LiveData 同样的原理也适用于编写 state。

您可以使用它重新创建整个构图

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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