-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathMainTestDispatcher.kt
71 lines (56 loc) · 2.2 KB
/
MainTestDispatcher.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test.internal
import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
/**
* Testable main dispatcher used by kotlinx-coroutines-test.
* It is a [MainCoroutineDispatcher] which delegates all actions to a settable delegate.
*/
// TODO implement delay
internal class TestMainDispatcher(private val mainFactory: MainDispatcherFactory) : MainCoroutineDispatcher() {
private var _delegate: CoroutineDispatcher? = null
private val delegate: CoroutineDispatcher get() {
if (_delegate != null) return _delegate!!
val newInstance = createDispatcher()
if (newInstance != null) {
_delegate = newInstance
return newInstance
}
// Return missing dispatcher, but do not set _delegate
return mainFactory.tryCreateDispatcher(emptyList())
}
@ExperimentalCoroutinesApi
override val immediate: MainCoroutineDispatcher
get() = (delegate as? MainCoroutineDispatcher)?.immediate ?: this
override fun dispatch(context: CoroutineContext, block: Runnable) {
delegate.dispatch(context, block)
}
@ExperimentalCoroutinesApi
override fun isDispatchNeeded(context: CoroutineContext): Boolean = delegate.isDispatchNeeded(context)
public fun setDispatcher(dispatcher: CoroutineDispatcher) {
_delegate = dispatcher
}
public fun resetDispatcher() {
_delegate = null
}
private fun createDispatcher(): CoroutineDispatcher? {
return try {
mainFactory.createDispatcher(emptyList())
} catch (cause: Throwable) {
null
}
}
}
internal class TestMainDispatcherFactory : MainDispatcherFactory {
override fun createDispatcher(allFactories: List<MainDispatcherFactory>): MainCoroutineDispatcher {
val originalFactory = allFactories.asSequence()
.filter { it !== this }
.maxBy { it.loadPriority } ?: MissingMainCoroutineDispatcherFactory
return TestMainDispatcher(originalFactory)
}
override val loadPriority: Int
get() = Int.MAX_VALUE
}