From d3977a461c228632d0c62717304d237e52a07227 Mon Sep 17 00:00:00 2001 From: takahirom Date: Wed, 4 May 2022 18:13:48 +0900 Subject: [PATCH] Add compose state molecule function --- .../kotlin/app/cash/molecule/molecule.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/molecule/molecule-runtime/src/commonMain/kotlin/app/cash/molecule/molecule.kt b/molecule/molecule-runtime/src/commonMain/kotlin/app/cash/molecule/molecule.kt index 57696005..38093af0 100644 --- a/molecule/molecule-runtime/src/commonMain/kotlin/app/cash/molecule/molecule.kt +++ b/molecule/molecule-runtime/src/commonMain/kotlin/app/cash/molecule/molecule.kt @@ -19,7 +19,10 @@ import androidx.compose.runtime.AbstractApplier import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.MonotonicFrameClock +import androidx.compose.runtime.MutableState import androidx.compose.runtime.Recomposer +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart.UNDISPATCHED @@ -77,6 +80,33 @@ fun CoroutineScope.launchMolecule( return flow!! } +/** + * Launch a coroutine into this [CoroutineScope] which will continually recompose `body` + * to produce a [State] stream of [T] values. + * + * The [CoroutineScope] in which this [State] is created must contain a + * [MonotonicFrameClock] key which controls when recomposition occurs. + */ +fun CoroutineScope.moleculeComposeState( + body: @Composable () -> T, +): State { + var mutableState: MutableState? = null + + launchMolecule( + emitter = { value -> + val outputFlow = mutableState + if (outputFlow != null) { + outputFlow.value = value + } else { + mutableState = mutableStateOf(value) + } + }, + body = body, + ) + + return mutableState!! +} + /** * Launch a coroutine into this [CoroutineScope] which will continually recompose `body` * to invoke [emitter] with each returned [T] value.