is there a way to delay the start of a coroutine? ...
# coroutines
b
is there a way to delay the start of a coroutine? I am writing a client for a REST API that has rate limits (soft, that I want to respect). So I would like to delay the start of each request if the time between the last request and current time is below the rate limit
✔️ 1
a
You might be looking for things like debouncing requests. It'll start after a delay and you can cancel it if another request comes through. Example: https://gist.github.com/elizarov/69ff0cf47d9ffe013bc6c1aeaf5af552
There's also throttle which ensures a set amount of time occurs between each request: https://gist.github.com/MarinaShaposhnikova/bcec5338814b93ecd6681877cb29bb7e
Note that both examples use obsolete apis though
b
that's throttle that I'm looking for
Thanks!
so I could set the throttle in the Channel itself so I can update it
a
Essentially. And then you'd add a receiver to the new channel to handle requests. There's also things called actors which you can look into. Not sure if it applies here as I'm not entirely familiar with it
b
I need to find a way to run the consummer
a
What exactly is your use case here? What do you expect to be returned if you want to call an api but it's too soon to do so? Do you want to wait the remaining amount of time or use an old response? If it's the latter, I have an example I wrote here: https://github.com/AllanWang/Frost-for-Facebook/blob/dev/app/src/main/kotlin/com/pitchedapps/frost/kotlin/Flyweight.kt It will call the api if the response has been previously called and is not too old to discard. The fetcher returns a deferred response, which you can then wait for. The code will be similar if you want to wait for new requests too. You just need to specify the delay before you fetch again, and you wouldn't need to keep the old responses
b
I need to wait
a
Then you can either use a continuation to force a wait or also return a deferred. The caller should perhaps manage a map of requests and the last time it was called. If it's too early, add a delay and then call your api, then fulfill your continuation/deferred value
b
I'm really new with coroutines. And it is for a TornadoFX app
with user interaction, so no problem making the user wait
a
Your platform won't really matter for the request logic. Just remember to run this outside of the main dispatcher. You may want to look at the docs first and maybe watch some youtube talks to get familiar with this first.
b
Yes I have issues understanding what is going to run and where to listen on the channel
thanks for the links!