Android Kotlin coroutine crashing on strict mode

The solution is to use your own dispatcher that you initialize without doing I/O on the main thread.

It's a bit tricky to implement because to avoid slowing down your app because of vsync enabled by default on Handler (could delay by up to 16ms code that doesn't need vsync at all), you have to use an API 28+ constructor, and use reflection for older versions of Android. After doing that, you can use the asCoroutineDispatcher() extension function for Handler, and use the resulting dispatcher.

To make it simpler for me, and others, I made a (small) library that provides a Dispatchers.MainAndroid extension that is lazily initialized without any I/O and can be used in place of Dispatchers.Main. It also integrated Lifecycle with coroutine scopes.

Here's the link where you can see how to get the dependency (available on jcenter) and how it is implemented: https://github.com/LouisCAD/Splitties/tree/master/modules/lifecycle-coroutines


The problem is that initializing Dispatchers.Main for Kotlin Coroutines is using a lot of disk time to read and checksum your JAR. This shouldn't happen.

This issue in Kotlin Coroutines was resolved with a workaround faster ServiceLoader. There's a newer version of Kotlin Coroutines you should use which offers a workaround ServiceLoader that does not checksum the JAR on disk.

The Google Android team working on the R8 optimizer is also creating an even better solution that will optimize out ServiceLoader reads entirely at the ProGuard step if you have ProGuard optimizations fully enabled with a new enough R8. That fix will be in Android Gradle Plugin 3.5.0 when used with R8.