voben
02/11/2020, 11:43 PMsuspend fun doSomething(): String {
val myFlow = flow { emit("hello") }
myFlow.collect { myString ->
return myString
}
}
Mark Murphy
02/11/2020, 11:44 PMFlow
will emit one item? Or are you looking to return the first emitted item?voben
02/11/2020, 11:45 PMMark Murphy
02/11/2020, 11:45 PMfirst()
operator: https://klassbook.commonsware.com/lessons/Flows%20and%20Channels/first-flow.htmlimport kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
suspend fun doSomething(): String {
val myFlow = flow { emit("hello") }
return myFlow.first()
}
fun main() {
GlobalScope.launch {
println(doSomething())
}
}
voben
02/11/2020, 11:54 PMMark Murphy
02/11/2020, 11:56 PMfirst()
collects the first item only. So:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
suspend fun doSomething(): String {
val myFlow = flow { emit("hello"); emit("world") }
return myFlow.first()
}
fun main() {
GlobalScope.launch {
println(doSomething())
}
}
still just prints hello
, even though the flow emits two items.Seri
02/12/2020, 6:23 PMFlow<T>.single()
if you want to guarantee that only one value is published. https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/single.html