From 31d86ffa9d193cbaad414d488cfc572d79e97bde Mon Sep 17 00:00:00 2001 From: Luca Tremamunno Date: Tue, 28 Oct 2025 13:53:42 +0100 Subject: [PATCH] Add ReactNativeDispatcher --- kotlinx-coroutines-core/js/src/CoroutineContext.kt | 5 ++++- kotlinx-coroutines-core/js/src/JSDispatcher.kt | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/kotlinx-coroutines-core/js/src/CoroutineContext.kt b/kotlinx-coroutines-core/js/src/CoroutineContext.kt index 4384943c42..455b27eeea 100644 --- a/kotlinx-coroutines-core/js/src/CoroutineContext.kt +++ b/kotlinx-coroutines-core/js/src/CoroutineContext.kt @@ -14,9 +14,12 @@ internal actual fun createDefaultDispatcher(): CoroutineDispatcher = when { // Check if we are in the browser and must use window.postMessage to avoid setTimeout throttling jsTypeOf(window) != UNDEFINED && window.asDynamic() != null && jsTypeOf(window.asDynamic().addEventListener) != UNDEFINED -> window.asCoroutineDispatcher() + // On react-native use setImmediate + jsTypeOf(navigator) != UNDEFINED && navigator != null && navigator.product == "ReactNative" -> + ReactNativeDispatcher // If process is undefined (e.g. in NativeScript, #1404), use SetTimeout-based dispatcher jsTypeOf(process) == UNDEFINED || jsTypeOf(process.nextTick) == UNDEFINED -> SetTimeoutDispatcher - // Fallback to NodeDispatcher when browser environment is not detected + // Fallback to NodeDispatcher when browser or react native environment is not detected else -> NodeDispatcher } diff --git a/kotlinx-coroutines-core/js/src/JSDispatcher.kt b/kotlinx-coroutines-core/js/src/JSDispatcher.kt index f0cd50a0b8..933e51db4b 100644 --- a/kotlinx-coroutines-core/js/src/JSDispatcher.kt +++ b/kotlinx-coroutines-core/js/src/JSDispatcher.kt @@ -39,6 +39,12 @@ internal object NodeDispatcher : SetTimeoutBasedDispatcher() { } } +internal object ReactNativeDispatcher : SetTimeoutBasedDispatcher() { + override fun scheduleQueueProcessing() { + setImmediate(messageQueue.processQueue) + } +} + internal actual class WindowMessageQueue actual constructor(private val window: W3CWindow) : MessageQueue() { private val messageName = "dispatchCoroutine" @@ -66,5 +72,7 @@ private external fun setTimeout(handler: dynamic, timeout: Int = definedExternal private external fun clearTimeout(handle: Int = definedExternally) +private external fun setImmediate(f: () -> Unit) + private fun setTimeout(window: Window, handler: () -> Unit, timeout: Int): Int = window.setTimeout(handler, timeout)