如果将List<Interface>
与LazyColumn一起使用,则会重新组合所有项,而如果我使用List<Implementation>
,则它会智能地跳过重新组合.
例如,如果我在可组合重组中使用示例1 MutableList
,则对列表中的所有加法操作的项进行重组,但在示例2中,它会智能地跳过.WHY?
例1:
val selectionState: MutableList<ViewItemScratch> = remember {
mutableStateListOf()
}
示例2:
val selectionState: MutableList<TitleViewItemScratch> = remember {
mutableStateListOf()
}
接口:
interface ViewItemScratch {
val identifier: Int
val layoutId: Int
@SuppressLint("NotConstructor")
@Composable
fun ViewItem(
lazyItemScope: LazyItemScope? = null,
rowScope: RowScope? = null,
columnScope: ColumnScope? = null
) {
}
}
实施类:
data class TitleViewItemScratch(
val index: Int,
val text: StringResolver,
val modifier: Modifier = Modifier,
override val identifier: Int = text.hashCode()
) : ViewItemScratch {
override val layoutId: Int
get() = R.id.compose_view_title_view_item
@Composable
override fun ViewItem(
lazyItemScope: LazyItemScope?, rowScope: RowScope?, columnScope: ColumnScope?
) {
Text(
modifier = modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(horizontal = 16.dp),
text = text.resolve(),
)
}
}
可组合的:
@Composable
private fun WithViewItemScratch() {
val selectionState: MutableList<ViewItemScratch> = remember {
mutableStateListOf()
}
val onButtonClick = remember {
{
selectionState.add(
TitleViewItemScratch(
index = selectionState.size + 1,
text = UIString("Hello world #${selectionState.size + 1}"),
identifier = selectionState.size + 1,
)
)
}
}
Column {
Button(onClick = {
onButtonClick.invoke()
}) {
Text(text = "Add")
}
LazyColumn {
items(
items = selectionState,
key = { viewItem: ViewItemScratch -> viewItem.identifier }
) { item ->
item.ViewItem()
}
}
}
}
编译报道(S):
restartable skippable fun ViewItem(
unused stable lazyItemScope: LazyItemScope? = @static null
unused stable rowScope: RowScope? = @static null
unused stable columnScope: ColumnScope? = @static null
unused <this>: ViewItemScratch
)
stable class TitleViewItemScratch {
stable val index: Int
stable val text: StringResolver
stable val color: CompassColor
stable val typography: CompassTypography
stable val modifier: Modifier
stable val identifier: Int
<runtime stability> = Stable
}
版面判断器重新组合:
带实现列表/具体类: