Andy Himberger
03/10/2023, 6:24 PMAndy Himberger
03/10/2023, 6:25 PMclass VM ... {
val componentMap: Map<String, Component>
get() = _componentMap
private val _componentMap = mutableStateMapOf<String, Component>()
}
@Composable
fun UsingMap() {
val vm = viewModels<VM>()
val componentMap = vm.componentMap
val filteredMap = remember(componentMap) {
componentMap.values.filterIsInstance<FooComponent>()
}
filteredMap.forEach{
//
}
}
Doing this instead works:
// Works, only way?
val filteredMap by remember {
derivedStateOf { componentMap.values.filterIsInstance<FooComponent>()
}
}
Which solves the remember case. Not sure about an EffectAlex Vanyo
03/10/2023, 6:54 PMremember, key and the effects use .equals to determine if the argument(s) have changed, and .equals is different than being @Stable and being observable for snapshot state
For arguments that are mutable, .equals must return true for the same instance, so remember will only run once for the same instance.
LazyListState is a good example where that is useful:
LaunchedEffect(lazyListState) {
snapshotFlow { lazyListState.layoutInfo.totalItemsCount }
.collect {
// use the new items count
}
}
The LaunchedEffect here will restart whenever the instance of LazyListState changes.
But then the internal properties of LazyListState can themselves change and we can observe them with snapshotFlow.
So something else you could try is remember(componentMap.toMap()) which creates an immutable copy to compare against for .equalsAndy Himberger
03/10/2023, 8:05 PM