https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bjonnh

01/04/2019, 10:22 PM
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

Allan Wang

01/04/2019, 10:23 PM
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

bjonnh

01/04/2019, 10:25 PM
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

Allan Wang

01/04/2019, 10:27 PM
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

bjonnh

01/04/2019, 10:29 PM
I need to find a way to run the consummer
a

Allan Wang

01/04/2019, 10:32 PM
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

bjonnh

01/04/2019, 10:33 PM
I need to wait
a

Allan Wang

01/04/2019, 10:34 PM
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

bjonnh

01/04/2019, 10:34 PM
I'm really new with coroutines. And it is for a TornadoFX app
with user interaction, so no problem making the user wait
a

Allan Wang

01/04/2019, 10:38 PM
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

bjonnh

01/04/2019, 10:39 PM
Yes I have issues understanding what is going to run and where to listen on the channel
thanks for the links!
5 Views