Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -77,6 +80,33 @@ fun <T> 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 <T> CoroutineScope.moleculeComposeState(
body: @Composable () -> T,
): State<T> {
var mutableState: MutableState<T>? = 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.
Expand Down