Teimatini Marin
03/18/2023, 12:21 AMimport kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
fun main() = runBlocking {
produceFlowNumbers()
.collect { // First collect
squareFlow(it)
.collect { // Second collect inside First collect
println(it)
}
}
println("Done!") // we are done
}
fun produceFlowNumbers() : Flow<Int> = flow {
var x = 1
while (x < 5) emit(x++) // infinite stream of integers starting from 1
}
fun squareFlow(number: Int): Flow<Int> = flow {
emit(number*number)
}
I have the feeling that I'm missing something here.
Any suggestion experts?ephemient
03/18/2023, 12:42 AMproduceFlowNumbers()
.flatMapConcat { squareFlow(it) }
.collect { println(it) }
Joffrey
03/18/2023, 4:47 AMsquareFlow
just to flatten them right away. Of you want to transform elements of a flow, you could simply use `.map`:
produceFlowNumbers().map { it * it }.collect { ... }
map
call.ephemient
03/18/2023, 5:53 AMtransform
may be more natural than flatMap
(depends on the usage)produceFlowNumbers()
.transform {
emit(it * it)
emit(it * it * it)
}