Chachako
08/18/2024, 11:00 AMvar show by remember { mutableBooleanStateOf(false) }
if (!show) SideEffect { show = true }
val enterAnim by ...
However, when I scroll the list, the show
state gets recomposed, making this approach unworkable, unless I use rememberSaveable
or do something like this:
@Composable
fun Item(item: ItemData) {
var appear by remember { mutableBooleanStateOf(item.attach) }
if (!item.attach) SideEffect {
item.attach = true
appear = true
}
}
But it feels strange, even though it's effective... So, does anyone have suggestions for a correct way to do this?Chachako
08/18/2024, 12:32 PMimport androidx.compose.runtime.Composable
import androidx.compose.runtime.currentCompositeKeyHash
import androidx.compose.runtime.staticCompositionLocalOf
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import myapp.common.getOrPut
@JvmInline
value class ItemStateRegistry(
private val inner: Int2ObjectOpenHashMap<Any> = Int2ObjectOpenHashMap()
) {
fun <T : Any> getOrPut(key: Int, init: () -> T): T {
@Suppress("UNCHECKED_CAST")
return inner.getOrPut(key, init) as T
}
}
val LocalItemStateRegistry = staticCompositionLocalOf<ItemStateRegistry> { noCompositionLocalProvided() }
@Composable
fun <T : Any> rememberItemState(init: () -> T): T {
val key = currentCompositeKeyHash
return LocalItemStateRegistry.current.getOrPut(key) { init() }
}
(also applies to remembering the one-time LOTTIE animation in lazy list)