gammanik
04/05/2020, 9:44 AMtseisel
04/05/2020, 9:55 AMrunBlocking
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.gammanik
04/05/2020, 9:58 AMmain
function and I wasn’t setting a dispatcher explicidly. This is the only one runBlocking
in the programtseisel
04/05/2020, 10:01 AMresponses
variable (that I expect to be of type List<Deferred<Collection<Person>>>
) ?gammanik
04/05/2020, 10:03 AMval responses: ArrayList<Deferred<Collection<Person>>> = ArrayList()
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)
}
}
tseisel
04/05/2020, 10:11 AMrunBlocking
, for example
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 functionsgammanik
04/05/2020, 10:17 AMsuggestDriversAsync
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 finishedtseisel
04/05/2020, 10:37 AMgammanik
04/05/2020, 10:49 AM<http://Dispatchers.IO|Dispatchers.IO>
to async
and now it’s perfect