android / codelab-kotlin-coroutines

Kotlin Coroutines codelab
Apache License 2.0
552 stars 268 forks source link

How to Inject Other Dispatchers to MainCoroutineScopeRule? #91

Open mikepalarz opened 4 years ago

mikepalarz commented 4 years ago

I saw this comment in MainCoroutineScopeRule and didn't fully understand what is meant by it:

https://github.com/googlecodelabs/kotlin-coroutines/blob/b71b981f8354a92fb3ebda37eceb7461e783d0bf/coroutines-codelab/start/src/test/java/com/example/android/kotlincoroutines/main/utils/MainCoroutineScopeRule.kt#L70

Is this comment saying that I can inject a TestCoroutineDispatcher into (for example) Dispatchers.IO within this rule? It's not clear to me how that can be done because neither the coroutines library nor the test library provide any means to override the other dispatchers.

Is this is suggesting to inject the dispatchers as parameters to suspend functions? For example:

suspend doSomeIO(dispatcher: CoroutineDispatcher = Dispatchers.IO) {
    launch(dispatcher) {
        // Some long-running IO operation
    }
}

And then in my test, I'd do the following:

class MyTestClass{

    @get:Rule
    val coroutineScope = MainCoroutineScopeRule()

    @Test
    fun myTest() {
        val foo = doSomeIO(coroutineScope.dispatcher)
        // Rest of the test, assertions, etc.
    }

}

If that's the case, then it's surely a workable solution. However, this comment needs to be clarified, it wasn't clear to me when I initially read it.