Hey! I have a weird question. I have a list of ob...
# coroutines
a
Hey! I have a weird question. I have a list of object and have to make a network call for every object, but they have to be made once a 10 seconds, and not faster. I was thinking, maybe I could somehow create a separate coroutine scope for each object and call a
delay
inside each call inside the
scope.launch
. Any suggestions would be very welcome, thank you!
j
I don't think you need a separate scope for each call (unless you do for other reasons), but otherwise that sounds reasonable, something like
Copy code
val deferreds = objects.mapIndexed { index, value -> 
        async {
            delay(index * 10_000L)
            println(value)
        }
    }
deferreds.awaitAll()
But then obviously doing your networking stuff instead of
println
­čÖé
g
You also can just delay in forEach, it looks unnecessary to launch all coroutines together and even start coroutine for every call
j
I guess it depends if you expect the network call to return within those 10 seconds, I was assuming they potentially could take longer and you'd want to start the next call even if the previous one hadn't returned. And launching coroutines is very cheap. A bigger problem with my snippet is that it completely ignores error handling, which you definitely want to consider in practice.
g
yep, makes sense, depends on required semantics, should time of request be a part of delay or not
a
Thank you for the tips!