Niklas Gürtler
02/12/2021, 3:42 PMfun fetchData (scope : CoroutineScope) : Pair<Deferred<Int>, Channel<Float>> {
// Start first operation
val r1 : Deferred<Int> = scope.async {
delay (200) // Pretend to do some work
42 // Return a result
}
val r2 = Channel<Float> ()
// Start second operation
scope.launch {
repeat (10) {
delay (it * 100L) // Pretend to do some work
r2.send(it.toFloat()) // Return one result
}
// Second operation done
r2.close()
}
return Pair(r1, r2)
}
fun main () {
val results = fetchData(GlobalScope)
runBlocking {
launch {
val res1 = results.first.await()
println("Result 1 : $res1")
}
launch {
for (elem in results.second) {
println ("Result 2 elem: $elem")
}
}
}
}
Without coroutines, I'd use a callback interface with functions onResult1(x:Int)
and onResult2(x : Float)
and call the first one once and the second one multiple times.wasyl
02/12/2021, 3:46 PMPair<Deferred<>, Channel<>>
then you can the await both separately. I imagine it’s not very different from having two separate functions.
I’d suggest using Flow
directly if you can instead of the channel, thoughNiklas Gürtler
02/12/2021, 3:49 PMwasyl
02/12/2021, 3:53 PMSharedFlow
but I’m not sure it would be better. Overall what you sent looks good to me 🙂 I’m not an expert thoughNiklas Gürtler
02/12/2021, 3:57 PM