• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines.internal
6 
7 import kotlinx.coroutines.*
8 import java.util.*
9 import kotlin.coroutines.*
10 
11 /**
12  * Name of the boolean property that enables using of [FastServiceLoader].
13  */
14 private const val FAST_SERVICE_LOADER_PROPERTY_NAME = "kotlinx.coroutines.fast.service.loader"
15 
16 // Lazy loader for the main dispatcher
17 internal object MainDispatcherLoader {
18 
19     private val FAST_SERVICE_LOADER_ENABLED = systemProp(FAST_SERVICE_LOADER_PROPERTY_NAME, true)
20 
21     @JvmField
22     val dispatcher: MainCoroutineDispatcher = loadMainDispatcher()
23 
loadMainDispatchernull24     private fun loadMainDispatcher(): MainCoroutineDispatcher {
25         return try {
26             val factories = if (FAST_SERVICE_LOADER_ENABLED) {
27                 FastServiceLoader.loadMainDispatcherFactory()
28             } else {
29                 // We are explicitly using the
30                 // `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
31                 // form of the ServiceLoader call to enable R8 optimization when compiled on Android.
32                 ServiceLoader.load(
33                         MainDispatcherFactory::class.java,
34                         MainDispatcherFactory::class.java.classLoader
35                 ).iterator().asSequence().toList()
36             }
37             @Suppress("ConstantConditionIf")
38             factories.maxBy { it.loadPriority }?.tryCreateDispatcher(factories)
39                 ?: createMissingDispatcher()
40         } catch (e: Throwable) {
41             // Service loader can throw an exception as well
42             createMissingDispatcher(e)
43         }
44     }
45 }
46 
47 /**
48  * If anything goes wrong while trying to create main dispatcher (class not found,
49  * initialization failed, etc), then replace the main dispatcher with a special
50  * stub that throws an error message on any attempt to actually use it.
51  *
52  * @suppress internal API
53  */
54 @InternalCoroutinesApi
tryCreateDispatchernull55 public fun MainDispatcherFactory.tryCreateDispatcher(factories: List<MainDispatcherFactory>): MainCoroutineDispatcher =
56     try {
57         createDispatcher(factories)
58     } catch (cause: Throwable) {
59         createMissingDispatcher(cause, hintOnError())
60     }
61 
62 /** @suppress */
63 @InternalCoroutinesApi
isMissingnull64 public fun MainCoroutineDispatcher.isMissing(): Boolean = this is MissingMainCoroutineDispatcher
65 
66 // R8 optimization hook, not const on purpose to enable R8 optimizations via "assumenosideeffects"
67 @Suppress("MayBeConstant")
68 private val SUPPORT_MISSING = true
69 
70 @Suppress("ConstantConditionIf")
71 private fun createMissingDispatcher(cause: Throwable? = null, errorHint: String? = null) =
72     if (SUPPORT_MISSING) MissingMainCoroutineDispatcher(cause, errorHint) else
73         cause?.let { throw it } ?: throwMissingMainDispatcherException()
74 
throwMissingMainDispatcherExceptionnull75 internal fun throwMissingMainDispatcherException(): Nothing {
76     throw IllegalStateException(
77         "Module with the Main dispatcher is missing. " +
78             "Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android' " +
79             "and ensure it has the same version as 'kotlinx-coroutines-core'"
80     )
81 }
82 
83 private class MissingMainCoroutineDispatcher(
84     private val cause: Throwable?,
85     private val errorHint: String? = null
86 ) : MainCoroutineDispatcher(), Delay {
87 
88     override val immediate: MainCoroutineDispatcher get() = this
89 
isDispatchNeedednull90     override fun isDispatchNeeded(context: CoroutineContext): Boolean =
91         missing()
92 
93     override suspend fun delay(time: Long) =
94         missing()
95 
96     override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle =
97         missing()
98 
99     override fun dispatch(context: CoroutineContext, block: Runnable) =
100         missing()
101 
102     override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) =
103         missing()
104 
105     private fun missing(): Nothing {
106         if  (cause == null) {
107             throwMissingMainDispatcherException()
108         } else {
109             val message = "Module with the Main dispatcher had failed to initialize" + (errorHint?.let { ". $it" } ?: "")
110             throw IllegalStateException(message, cause)
111         }
112     }
113 
toStringnull114     override fun toString(): String = "Dispatchers.Main[missing${if (cause != null) ", cause=$cause" else ""}]"
115 }
116 
117 /**
118  * @suppress
119  */
120 @InternalCoroutinesApi
121 public object MissingMainCoroutineDispatcherFactory : MainDispatcherFactory {
122     override val loadPriority: Int
123         get() = -1
124 
125     override fun createDispatcher(allFactories: List<MainDispatcherFactory>): MainCoroutineDispatcher {
126         return MissingMainCoroutineDispatcher(null)
127     }
128 }
129