https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

voben

02/11/2020, 11:43 PM
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

Mark Murphy

02/11/2020, 11:44 PM
Are you guaranteed that the
Flow
will emit one item? Or are you looking to return the first emitted item?
v

voben

02/11/2020, 11:45 PM
Looking to return the first item emitted
m

Mark Murphy

02/11/2020, 11:45 PM
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

voben

02/11/2020, 11:54 PM
How would I approach this if the flow isn’t guaranteed to emit only one item?
m

Mark Murphy

02/11/2020, 11:56 PM
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

Seri

02/12/2020, 6:23 PM
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
2 Views