Skip to content

Ensure consistent delay behavior in immediate across platforms #4432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion kotlinx-coroutines-core/nativeDarwin/src/Dispatchers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private class DarwinMainDispatcher(
val timer = Timer()
val timerBlock: TimerBlock = {
timer.dispose()
continuation.resume(Unit)
with(continuation) { resumeUndispatched(Unit) }
}
timer.start(timeMillis, timerBlock)
continuation.disposeOnCancellation(timer)
Expand Down
21 changes: 21 additions & 0 deletions test-utils/common/src/MainDispatcherTestBase.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package kotlinx.coroutines.testing

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.test.*

abstract class MainDispatcherTestBase: TestBase() {
Expand Down Expand Up @@ -151,6 +152,26 @@ abstract class MainDispatcherTestBase: TestBase() {
}
}

/** Tests that [delay] runs the task inline instead of explicitly scheduling it
* (which can be observed by the event loop's ordering). */
@Test
@NoJs @NoWasmWasi @NoWasmJs // This test does not work for environments with a single always-on event loop
fun testUndispatchedAfterDelay() = runTestOrSkip {
launch(Dispatchers.Main.immediate) {
val channel = Channel<Unit>()
expect(1)
launch {
channel.receive()
expect(3)
}
delay(100)
checkIsMainThread()
expect(2)
channel.send(Unit)
finish(4)
}
}

private suspend fun <R> withMainScope(block: suspend CoroutineScope.() -> R): R {
MainScope().apply {
return block().also { coroutineContext[Job]!!.cancelAndJoin() }
Expand Down