Would this be a correct implementation of interval...
# coroutines
m
Would this be a correct implementation of interval?
o
assuming you want it 10ms after the completion of the last block, yes if you want it every 10ms exactly (e.g. if
block()
takes 5ms to execute, you want it run again in 5ms), no
java's
ScheduledExecutorService
differs between these with the terms "fixed rate" and "fixed delay" -- your current example is "fixed delay", not "fixed rate"
m
good point. Then I could use
measureTimeMillis
to achieve fixed rate
but technical characteristic aside I was wondering if I made any coroutine cardinal mistake or something
o
I don't think so, it looks fine to me
👍 1
m
interval is quite useful, it seems weird it's not included in coroutine standard lib
o
I think they try to keep it as small as possible
the essence of interval is really just "loop and delay", it's not very complex to implement, so they may think it is not necessary to add it to stdlib
m
that's fair, implementation looks trivial
w
And the below version is fine as well as long as I call it in a scope, using
launch { interval(123) { doX() } }
, right?
Copy code
suspend fun interval(time: Long, block: suspend () -> Unit) {
    while (true) {
        block()
        delay(time)
    }
}
I’m still kind of confused when to prefer an extension on
CoroutineScope
(or is passing scope better?) vs having a
suspend fun
o
that works fine as well, yes. I guess it's just a matter of preference, extensions on
CoroutineScope
are for "forking" a new coroutine that runs async,
suspend fun
is for normal sync behavior
👌 1
w
Great one-sentence explanation👌 Thanks! So I suppose these are also purely preference, or is there some practical difference as well? -
fun CoroutineScope.doX()
vs
fun doX(scope: CoroutineScope)
- implementing
CoroutineScope
by a class vs keeping the scope in a field (as long as I implement scope only for convenience, e.g. to call
launch
easily)
o
yes, that is just preference as well
🙏 1