This message was deleted.
# coroutines
s
This message was deleted.
j
You need to inject the clock into that function via a parameter and then use the virtual time clock in your test.
j
Copy code
context(Clock)
	suspend inline fun <T> slowdown(duration: Duration, block: () -> T): T {
		var result: T
		val timeTaken = this@Clock.measureTime {
			result = block()
		}
		delay(duration - timeTaken)
		return result
	}
then in
runTest
scope, I should use
currentTime
and in normal
runBlocking
scope, `System.currentTimeInMilliSeconds`before and after
block
... I guess that'll work Thanks Jake!
e
unrelated, but you could
Copy code
val (result, timeTaken) = measureTimedValue { ... }
I'd use a
TimeSource
instead of
Clock
, defaulting to
Monotonic
, but either way you do have to provide the test value yourself since there isn't a public way of extracting it from the coroutine context
So you could use
runTest { testTimeSource.measureTimedValue {} }
e
yes, but the
slowdown
function can't pull that out of its context - the test still has to pass it along
h
Okay that's true. But the
testTimeSource
supports delay-skipping.
e
yep, that's basically what I was recommending
for this case in particular,
Copy code
suspend fun <T> slowdown(duration: Duration, block: () -> T): T = coroutineScope {
    launch { delay(duration) }
    block()
}
would achieve the same result without having to deal with time, but in general you do need to use the test timesource or create a fake clock based on test time in order to work with test delay skipping