A
A
arteskin2021-11-20 14:32:52
Android
arteskin, 2021-11-20 14:32:52

How to redo the code so that the correct values ​​get into the state?

Flow emits 3 values ​​that need to be written to MyState, however, with this approach, only the last value (3) gets into state, which is expected. How to remake this code so that first gets 1, second 2 and third, respectively, 3?

data class MyState(
    val first: Int = 0,
    val second: Int = 0,
    val third: Int = 0
)

fun producer(): Flow<Int> = flow {
    for (i in 1..3) {
        emit(i)
    }
}

suspend fun main(){

    val state = mutableStateOf(MyState())

    coroutineScope {
        producer().onEach {
            state.value = MyState(
                first = it,
                second = it,
                third = it
            )
        }.launchIn(this)
    }

    println(state)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacen11, 2021-11-20
@arteskin

no way. It doesn't work like that and it shouldn't. And nobody does that. I don’t understand the case, what is really needed?
Of course, the data can be saved for each receipt, but why?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question