https://kotlinlang.org logo
Title
m

Maciek

07/22/2020, 6:24 AM
Would this be a correct implementation of interval?
o

octylFractal

07/22/2020, 6:26 AM
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

Maciek

07/22/2020, 6:28 AM
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

octylFractal

07/22/2020, 6:29 AM
I don't think so, it looks fine to me
👍 1
m

Maciek

07/22/2020, 6:29 AM
interval is quite useful, it seems weird it's not included in coroutine standard lib
o

octylFractal

07/22/2020, 6:30 AM
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

Maciek

07/22/2020, 6:35 AM
that's fair, implementation looks trivial
w

wasyl

07/22/2020, 7:02 AM
And the below version is fine as well as long as I call it in a scope, using
launch { interval(123) { doX() } }
, right?
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

octylFractal

07/22/2020, 7:04 AM
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

wasyl

07/22/2020, 7:12 AM
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

octylFractal

07/22/2020, 7:12 AM
yes, that is just preference as well
🙏 1