Skip to content

Commit 915347c

Browse files
authored
CoroutineDispatcher.asExecutor() to respect isDispatchNeeded (#3683)
Calling `Dispatchers.Main.immediate.asExecutor().execute { ... }` should respect the fact that it's immediate and avoid dispatch (and posting to the Looper) when in the right context.
1 parent 11d7ac0 commit 915347c

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

kotlinx-coroutines-core/jvm/src/Executors.kt

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,14 @@ public fun CoroutineDispatcher.asExecutor(): Executor =
108108
(this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this)
109109

110110
private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor {
111-
override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block)
111+
override fun execute(block: Runnable) {
112+
if (dispatcher.isDispatchNeeded(EmptyCoroutineContext)) {
113+
dispatcher.dispatch(EmptyCoroutineContext, block)
114+
} else {
115+
block.run()
116+
}
117+
}
118+
112119
override fun toString(): String = dispatcher.toString()
113120
}
114121

kotlinx-coroutines-core/jvm/test/ExecutorsTest.kt

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,22 @@ class ExecutorsTest : TestBase() {
8181
finish(4)
8282
}
8383

84+
@Test
85+
fun testCustomDispatcherToExecutorDispatchNotNeeded() {
86+
expect(1)
87+
val dispatcher = object : CoroutineDispatcher() {
88+
override fun isDispatchNeeded(context: CoroutineContext) = false
89+
90+
override fun dispatch(context: CoroutineContext, block: Runnable) {
91+
fail("should not dispatch")
92+
}
93+
}
94+
dispatcher.asExecutor().execute {
95+
expect(2)
96+
}
97+
finish(3)
98+
}
99+
84100
@Test
85101
fun testTwoThreads() {
86102
val ctx1 = newSingleThreadContext("Ctx1")
@@ -106,4 +122,4 @@ class ExecutorsTest : TestBase() {
106122
dispatcher.close()
107123
check(executorService.isShutdown)
108124
}
109-
}
125+
}

0 commit comments

Comments
 (0)