• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 @file:JvmName("TestDispatchers")
5 
6 package kotlinx.coroutines.test
7 
8 import kotlinx.coroutines.*
9 import kotlinx.coroutines.test.internal.*
10 import kotlin.jvm.*
11 
12 /**
13  * Sets the given [dispatcher] as an underlying dispatcher of [Dispatchers.Main].
14  * All subsequent usages of [Dispatchers.Main] will use the given [dispatcher] under the hood.
15  *
16  * Using [TestDispatcher] as an argument has special behavior: subsequently-called [runTest], as well as
17  * [TestScope] and test dispatcher constructors, will use the [TestCoroutineScheduler] of the provided dispatcher.
18  *
19  * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
20  */
21 @ExperimentalCoroutinesApi
setMainnull22 public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) {
23     require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" }
24     getTestMainDispatcher().setDispatcher(dispatcher)
25 }
26 
27 /**
28  * Resets state of the [Dispatchers.Main] to the original main dispatcher.
29  *
30  * For example, in Android, the Main thread dispatcher will be set as [Dispatchers.Main].
31  * This method undoes a dependency injection performed for tests, and so should be used in tear down (`@After`) methods.
32  *
33  * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
34  */
35 @ExperimentalCoroutinesApi
resetMainnull36 public fun Dispatchers.resetMain() {
37     getTestMainDispatcher().resetDispatcher()
38 }
39