-
-
Save PatilShreyas/3284e8c4916893cbba10340d0ca89b89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class TransformedStateFlow<T>( | |
private val getValue: () -> T, | |
private val flow: Flow<T> | |
) : StateFlow<T> { | |
override val replayCache: List<T> get() = listOf(value) | |
override val value: T get() = getValue() | |
override suspend fun collect(collector: FlowCollector<T>): Nothing = | |
coroutineScope { flow.stateIn(this).collect(collector) } | |
} | |
/** | |
* Returns [StateFlow] from [flow] having initial value from calculation of [getValue] | |
*/ | |
fun <T> stateFlow( | |
getValue: () -> T, | |
flow: Flow<T> | |
): StateFlow<T> = TransformedStateFlow(getValue, flow) | |
/** | |
* Combines all [stateFlows] and transforms them into another [StateFlow] with [transform] | |
*/ | |
inline fun <reified T, R> combineStates( | |
vararg stateFlows: StateFlow<T>, | |
crossinline transform: (Array<T>) -> R | |
): StateFlow<R> = stateFlow( | |
getValue = { transform(stateFlows.map { it.value }.toTypedArray()) }, | |
flow = combine(*stateFlows) { transform(it) } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment