Skip to content

Commit ecc68f1

Browse files
committed
Use NodeDispatcher on ReactNative
Fixes #236
1 parent eb4f9be commit ecc68f1

File tree

1 file changed

+12
-1
lines changed
  • js/kotlinx-coroutines-core-js/src/main/kotlin/kotlinx/coroutines/experimental

1 file changed

+12
-1
lines changed

js/kotlinx-coroutines-core-js/src/main/kotlin/kotlinx/coroutines/experimental/CoroutineContext.kt

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,25 @@ public actual object Unconfined : CoroutineDispatcher() {
3636
override fun toString(): String = "Unconfined"
3737
}
3838

39+
private external val navigator: dynamic
40+
private const val UNDEFINED = "undefined"
41+
3942
/**
4043
* This is the default [CoroutineDispatcher] that is used by all standard builders like
4144
* [launch], [async], etc if no dispatcher nor any other [ContinuationInterceptor] is specified in their context.
4245
*/
4346
@Suppress("PropertyName", "UnsafeCastFromDynamic")
4447
public actual val DefaultDispatcher: CoroutineDispatcher = when {
48+
// Check if we are running under ReactNative. We have to use NodeDispatcher under it.
49+
// The problem is that ReactNative has a `window` object with `addEventListener`, but it does not really work.
50+
// For details see https://github.com/Kotlin/kotlinx.coroutines/issues/236
51+
// The check for ReactNative is based on https://github.com/facebook/react-native/commit/3c65e62183ce05893be0822da217cb803b121c61
52+
jsTypeOf(navigator) != UNDEFINED && navigator != null && navigator.product == "ReactNative" ->
53+
NodeDispatcher()
4554
// Check if we are in the browser and must use window.postMessage to avoid setTimeout throttling
46-
jsTypeOf(window) != "undefined" && jsTypeOf(window.asDynamic().addEventListener) != "undefined" -> window.asCoroutineDispatcher()
55+
jsTypeOf(window) != UNDEFINED && window.asDynamic() != null && jsTypeOf(window.asDynamic().addEventListener) != UNDEFINED ->
56+
window.asCoroutineDispatcher()
57+
// Fallback to NodeDispatcher when browser environment is not detected
4758
else -> NodeDispatcher()
4859
}
4960

0 commit comments

Comments
 (0)