Hey, sorta new here, coming from Golang. I was af...
# getting-started
a
Hey, sorta new here, coming from Golang. I was after a replacement for
waitGroup
, build my own, shockingly bad one...
Copy code
// 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/ recorded
r
e
Just use structured concurrency and you will not need waitgroup at all. On side note, you’ll get better help in #coroutines channel.
e
What Roman said. Because coroutines use structured concurrency, you can wrap your code in a suspending function or
runBlocking { }
, 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.
Updated code will look like this: