Skip to content

Instantly share code, notes, and snippets.

@alaershov
Created August 1, 2023 10:04
Show Gist options
  • Save alaershov/373b4dc7024d4645c83a5007c2bce1e2 to your computer and use it in GitHub Desktop.
Save alaershov/373b4dc7024d4645c83a5007c2bce1e2 to your computer and use it in GitHub Desktop.
Decompose Value to State Flow
private class ValueStateFlow<T : Any>(
private val store: Value<T>,
) : StateFlow<T> {
override val value: T get() = store.value
override val replayCache: List<T> get() = listOf(store.value)
override suspend fun collect(collector: FlowCollector<T>): Nothing {
val flow = MutableStateFlow(store.value)
val observer: (T) -> Unit = { flow.value = it }
store.subscribe(observer)
try {
flow.collect(collector)
} finally {
store.unsubscribe(observer)
}
}
}
val <T : Any> Value<T>.stateFlow: StateFlow<T>
get() = ValueStateFlow(store = this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment