Ani Mehta
02/12/2020, 11:27 PMwaitGroup
, build my own, shockingly bad one...
// TODO: Fix this hacky parallelism
var awaitingResponse = 0
for (v in needsResponses) {
GlobalScope.launch {
while (awaitingResponse >= 30) {
delay(5)
}
awaitingResponse++
// send API request, record response
awaitingResponse--
}
}
sleep(1000) // needed in order to not just skip before any request is sent off
while (awaitingResponse > 0) {
sleep(5000)
}
For reference it iterates over a map in parallel, what's a better way of doing this? There's an issue currently where it sometimes proceeds before all responses are fetched/ recordedRobert
02/13/2020, 7:41 AMelizarov
02/13/2020, 11:29 AMEvan R.
02/13/2020, 8:18 PMrunBlocking { }
, then throw your for loop in a coroutineScope { }
, drop GlobalScope
, and the coroutineScope will both:
1. Wait for all launched coroutines to complete
2. Throw any exception from said coroutines and automatically cancel the others
Coroutines handles a lot of stuff that goroutines don’t.Evan R.
02/13/2020, 8:22 PM