```suspend fun <T> ???(millis: Long, action:...
# coroutines
u
Copy code
suspend fun <T> ???(millis: Long, action: suspend () -> T): T {
    val start = System.currentMillis()
    val value = action()
    val end = System.currentMillis()
    val took = end - start
    if (took < millis) {
        delay(millis - took)
    }
    return value
}
does this have a name already? it makes sure the suspend function takes atleast N millis, so its not too fast its not debounce since its calcualtes the delay …so I guess I need my own name
r
This sounds like a "constant time" operation, which is important in cryptography to prevent timing attacks (e.g. https://codahale.com/a-lesson-in-timing-attacks/), albeit not exactly. I don't know if there's a name for it. I'd be inclined to just name it something unsexy like
runForAtLeast(1000) { }
1
u
yea buts not really constant, its min constrained 😄
😅 1
e
better to build it up out of existing primitives,
Copy code
coroutineScope {
    launch {
        delay(millis)
    }
    action()
}
👌 4
👍 4
u
don’t I need to launch the action as well there?
r
No.
coroutineScope
will wait for all child coroutines to finish before it returns, so if
action()
completes but
delay()
is still running, it will wait.
This function returns as soon as the given block and all its children coroutines are completed
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html
u
I see, I thought it only waited for launched stuff for some reason, thanks
m
Watch out that with
action()
outside the
launch
block, any side effects from
action
will take place before the delay.
e
that is the intention here
👍 2