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

gammanik

04/05/2020, 9:44 AM
Is awaitAll workitg as expected here? I have 10 Deferred in my responses list (highlighted in terminal). The weird thind that they all are marked as completed. But I can iterate only to a lesser amount at the end. There are only 3 in the output. BTW if I uncomment //delay(6000) I’ll see all 10 responses What am I doing wrong?
t

tseisel

04/05/2020, 9:55 AM
This may be related to awaiting i a different
runBlocking
block than the one where you launched your
async
coroutines. On what dispatcher are you launching coroutines ? Is it single-threaded ? Be aware that you should try to avoid using `runBlocking`: it has been designed to bridge normal code to the coroutine world in specific situations, for example the
main
function.
g

gammanik

04/05/2020, 9:58 AM
I’m calling it from
main
function and I wasn’t setting a dispatcher explicidly. This is the only one
runBlocking
in the program
t

tseisel

04/05/2020, 10:01 AM
Could you please share the declaration of the
responses
variable (that I expect to be of type
List<Deferred<Collection<Person>>>
) ?
g

gammanik

04/05/2020, 10:03 AM
Sure:
Copy code
val responses: ArrayList<Deferred<Collection<Person>>> = ArrayList()
Copy code
for (passenger in passengers) {
    val suggestedDrivers = suggestDriversAsync(passenger, drivers)
    println("Passenger point: ${passenger.finishPoint.latitude}, ${passenger.finishPoint.longitude}")

    GlobalScope.launch {
        responses.add(suggestedDrivers)
    }
}

runBlocking {
    val res: List<Collection<Person>> = responses.awaitAll()
    for (el in res) {
        println(el)
    }
}
t

tseisel

04/05/2020, 10:11 AM
Some remarks: 1. You should try to wrap the whole code in
runBlocking
, for example
Copy code
fun main() = runBlocking<Unit> {
    val responses = ...
    [...]
    val res = responses.awaitAll()
}
2. Why launch a coroutine in
GlobalScope
to add
suggestedDrivers
to the list ? Its not an operation that requires calling suspend functions
g

gammanik

04/05/2020, 10:17 AM
suggestDriversAsync
returns
Deferred<Collection<Person>>
If I wrap the whole code in
runblocking
I’ll send requests syncroniously I guess. So I wanted to send all the requests at once and then wait when they all are gonna be finished
t

tseisel

04/05/2020, 10:37 AM
I wrote this sample based on your code https://pl.kotl.in/N0HVVa2T5
g

gammanik

04/05/2020, 10:49 AM
Thank you! Great example. I’ve just added
<http://Dispatchers.IO|Dispatchers.IO>
to
async
and now it’s perfect
3 Views