Kotlin coroutine unit test fails with “Module with the Main dispatcher had failed to initialize”

UPDATED 2023 Add the following dependency on your gradle. Documentation here testImplementation “org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version” Add the following Custom TestRule as a utility for your tests // Reusable JUnit4 TestRule to override the Main dispatcher @OptIn(ExperimentalCoroutinesApi::class) class MainDispatcherRule( private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher() ) : TestWatcher() { override fun starting(description: Description) { Dispatchers.setMain(testDispatcher) } override fun … Read more

How can I send items to a Kotlin.Flow (like a Behaviorsubject)

If you want to get the latest value on subscription/collection you should use a ConflatedBroadcastChannel: private val channel = ConflatedBroadcastChannel<Boolean>() This will replicate BehaviourSubject, to expose the channel as a Flow: // Repository fun observe() { return channel.asFlow() } Now to send an event/value to that exposed Flow simple send to this channel. // Repository … Read more

When to use coroutineScope vs supervisorScope?

The best way to explain the difference is to explain the mechanism of coroutineScope. Consider this code: suspend fun main() = println(compute()) suspend fun compute(): String = coroutineScope { val color = async { delay(60_000); “purple” } val height = async<Double> { delay(100); throw HttpException() } “A %s box %.1f inches tall”.format(color.await(), height.await()) } compute() … Read more

Coroutine scope on Application class android

NO , GlobalScope will NOT be suitable for Application instance. As mention here in this article here: There are multiple reasons why you shouldn’t use GlobalScope: Promotes hard-coding values. It might be tempting to hardcode Dispatchers if you use GlobalScope straight-away. That’s a bad practice! It makes testing very hard. As your code is going … Read more