xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-test/common/src/TestDispatchers.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)
1 @file:JvmName("TestDispatchers")
2 
3 package kotlinx.coroutines.test
4 
5 import kotlinx.coroutines.*
6 import kotlinx.coroutines.test.internal.*
7 import kotlin.jvm.*
8 
9 /**
10  * Sets the given [dispatcher] as an underlying dispatcher of [Dispatchers.Main].
11  * All subsequent usages of [Dispatchers.Main] will use the given [dispatcher] under the hood.
12  *
13  * Using [TestDispatcher] as an argument has special behavior: subsequently-called [runTest], as well as
14  * [TestScope] and test dispatcher constructors, will use the [TestCoroutineScheduler] of the provided dispatcher.
15  *
16  * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
17  */
18 @ExperimentalCoroutinesApi
setMainnull19 public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) {
20     require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" }
21     getTestMainDispatcher().setDispatcher(dispatcher)
22 }
23 
24 /**
25  * Resets state of the [Dispatchers.Main] to the original main dispatcher.
26  *
27  * For example, in Android, the Main thread dispatcher will be set as [Dispatchers.Main].
28  * This method undoes a dependency injection performed for tests, and so should be used in tear down (`@After`) methods.
29  *
30  * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
31  */
32 @ExperimentalCoroutinesApi
resetMainnull33 public fun Dispatchers.resetMain() {
34     getTestMainDispatcher().resetDispatcher()
35 }
36