How do I return a value from a flow? Trying to ret...
# coroutines
v
How do I return a value from a flow? Trying to return the myString value
Copy code
suspend fun doSomething(): String {
   val myFlow = flow { emit("hello") }
   myFlow.collect { myString ->
        return myString
   }
}
m
Are you guaranteed that the
Flow
will emit one item? Or are you looking to return the first emitted item?
v
Looking to return the first item emitted
m
Copy code
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

suspend fun doSomething(): String {
   val myFlow = flow { emit("hello") }
   return myFlow.first()
}

fun main() {
  GlobalScope.launch {
    println(doSomething())
  }
}
v
How would I approach this if the flow isn’t guaranteed to emit only one item?
m
first()
collects the first item only. So:
Copy code
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.
s
You can also use
Flow<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