とあるLambdaの中で読み込まれたStateObjectを把握します。
環境
Jetpack Compose Desktopですが、Androidでも動きは同じはずです。
- Runtime 1.1
コード
Snapshot.observe
で読み込まれたStateObjectを把握する事ができます。
derivedStateOf
の内部で使われているものです。読み込まれたStateObjectに変更があった時に再計算を行わせています。
@Composable private fun Content() { Column { var count by remember { mutableStateOf(0) } val result = Snapshot.observe( readObserver = { if (it === this) return@observe if (it is StateObject) { println("class ${it::class}") println("value $it") } }, writeObserver = null, block = { count >= 1 // read state object "count" }, ) LaunchedEffect(Unit) { delay(1000) count++ delay(1000) count++ } Text("count=$count") Text("more than 1=$result") } }
class class androidx.compose.runtime.SnapshotMutableStateImpl (Kotlin reflection is not available) value MutableState(value=0)@211609400 class class androidx.compose.runtime.SnapshotMutableStateImpl (Kotlin reflection is not available) value MutableState(value=1)@211609400 class class androidx.compose.runtime.SnapshotMutableStateImpl (Kotlin reflection is not available) value MutableState(value=2)@211609400
おわりに
まぁ実務で Snapshot.observe
を使うことは無いでしょうが、 derivedStateOf
の動作の理解の役には立つでしょう。