Created
August 1, 2023 10:04
-
-
Save alaershov/373b4dc7024d4645c83a5007c2bce1e2 to your computer and use it in GitHub Desktop.
Decompose Value to State Flow
This file contains hidden or 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 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