1 /* 2 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 @file:Suppress("unused") 5 @file:JvmName("TestDispatchers") 6 7 package kotlinx.coroutines.test 8 9 import kotlinx.coroutines.* 10 import kotlinx.coroutines.test.internal.* 11 12 /** 13 * Sets the given [dispatcher] as an underlying dispatcher of [Dispatchers.Main]. 14 * All consecutive usages of [Dispatchers.Main] will use given [dispatcher] under the hood. 15 * 16 * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist. 17 */ 18 @ExperimentalCoroutinesApi setMainnull19public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) { 20 require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" } 21 val mainDispatcher = Dispatchers.Main 22 require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." } 23 mainDispatcher.setDispatcher(dispatcher) 24 } 25 26 /** 27 * Resets state of the [Dispatchers.Main] to the original main dispatcher. 28 * For example, in Android Main thread dispatcher will be set as [Dispatchers.Main]. 29 * Used to clean up all possible dependencies, should be used in tear down (`@After`) methods. 30 * 31 * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist. 32 */ 33 @ExperimentalCoroutinesApi resetMainnull34public fun Dispatchers.resetMain() { 35 val mainDispatcher = Dispatchers.Main 36 require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." } 37 mainDispatcher.resetDispatcher() 38 } 39