Is there a way to do something in a composable bef...
# compose
c
Is there a way to do something in a composable before the items in a lazy list appear or disappear? This would allow me to have full control over my animations...😵‍💫 I tried doing this within the item:
Copy code
var 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:
Copy code
@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?
Finally... I just chose to wrap it simply:
Copy code
import 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)