0

Android’s LiveData can be observed and changed anywhere without a coroutine with its observeForever() . How to do the same with MutableStateFlow that became a modern alternative to it (with Compose)?

Currently I made a workable work-around but it has a cascade design and boilerplate code.

    @Test
    fun mutableStateFlow() {
        val bl = MutableStateFlow(3)
        val bp = bl.map { it * 0.2f }
        fun getBp() = runBlocking { return@runBlocking bp.stateIn(CoroutineScope(Dispatchers.Default)) }

        val ut = bp.map { (it * up).toInt() }
        fun getUt() = runBlocking { //ReadonlyStateFlow is a private class
            return@runBlocking ut.stateIn(CoroutineScope(Dispatchers.Default))
        }

        assertEquals(6, getUt().value)

        bl.value = 4
        assertEquals(8, getUt().value)
    }

Or can use a class:

data class Flowable<T>(
    val flow: Flow<T>
) {
    val value: T
        get() = runBlocking { return@runBlocking flow.stateIn(CoroutineScope(Dispatchers.Default)).value }
}

MutableStateFlow is only the first one variable here and stateIn provides only ReadonlyStateFlow that is a private class and can't be transformed to MutableStateFlow (cause it's private) even if it was designed to be possible.

Psijic
  • 743
  • 7
  • 20

0 Answers0