Skip to content

Commit

Permalink
Some more useful APIs for avoiding state production when inactive.
Browse files Browse the repository at this point in the history
  • Loading branch information
avelicu committed Jan 27, 2025
1 parent f1ea144 commit b7f258c
Showing 1 changed file with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ package app.cash.molecule
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.suspendCancellableCoroutine

internal class MoleculeActiveContextElement(
val isMoleculeActive: StateFlow<Boolean>,
Expand Down Expand Up @@ -78,6 +82,13 @@ public suspend fun CoroutineScope.repeatWhileMoleculeActive(block: suspend () ->
runBlockWhenActive(moleculeActiveFlow, block)
}

/**
* Suspends until the Molecule is active.
*/
public suspend fun CoroutineScope.awaitMoleculeActive() {
awaitActive(moleculeActiveFlow)
}

private suspend fun runBlockWhenActive(
moleculeActiveFlow: StateFlow<Boolean>,
block: suspend () -> Unit,
Expand All @@ -87,3 +98,7 @@ private suspend fun runBlockWhenActive(
block()
}
}

private suspend fun awaitActive(moleculeActiveFlow: StateFlow<Boolean>) {
moleculeActiveFlow.first { it }
}

0 comments on commit b7f258c

Please sign in to comment.