Skip to content

Commit

Permalink
Use NodeDispatcher on ReactNative
Browse files Browse the repository at this point in the history
  • Loading branch information
elizarov committed Mar 5, 2018
1 parent eb4f9be commit ecc68f1
Showing 1 changed file with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,25 @@ public actual object Unconfined : CoroutineDispatcher() {
override fun toString(): String = "Unconfined"
}

private external val navigator: dynamic
private const val UNDEFINED = "undefined"

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

Expand Down

0 comments on commit ecc68f1

Please sign in to comment.