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
Joris PZ
11/11/2020, 1:58 PM
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()
Joris PZ
11/11/2020, 1:59 PM
But then obviously doing your networking stuff instead of
println
🙂
g
gildor
11/11/2020, 3:11 PM
You also can just delay in forEach, it looks unnecessary to launch all coroutines together and even start coroutine for every call
j
Joris PZ
11/11/2020, 3:41 PM
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
gildor
11/11/2020, 3:45 PM
yep, makes sense, depends on required semantics, should time of request be a part of delay or not