How can I convert Value to Flow ?
# decompose
v
How can I convert Value to Flow ?
a
You can try the following code.
Copy code
fun <T : Any> Value<T>.toStateFlow(): StateFlow<T> = ValueStateFlow(this)

private class ValueStateFlow<out T : Any>(private val source: Value<T>) : StateFlow<T> {

    override val value: T
        get() = source.value

    override val replayCache: List<T>
        get() = listOf(source.value)

    override suspend fun collect(collector: FlowCollector<T>): Nothing {
        val flow = MutableStateFlow(source.value)
        val disposable = source.observe { flow.value = it }

        try {
            flow.collect(collector)
        } finally {
            disposable.cancel()
        }
    }
}
v
Thanks will try this out
d
Arkadi, do you plan to include this extension in some of the future releases?
a
There were no plans yet.
🆗 1
102 Views