Learning Coroutine

7 Gotchas When Explore Kotlin Coroutine

Little aha moments when learning Kotlin Coroutine

Photo by Alex Sheldon on Unsplash

I took my year-end break to explore more on Kotlin Coroutine Ecosystem. I’m surprised to find out many unexpected behaviors. Some are documented (I found them later), and some are not (or at least I haven’t found them).

To get to the answer, I post on StackOverflow, pull my hair, take a nap to get some idea on how to debug to find the answer.

Sharing here for the benefit of all.

Note: this is assuming you have some Coroutine basic knowledge. If you don’t check out the below first.
1. Differentiating Thread and Coroutine
2. Understanding Suspend Function
3. Kotlin Coroutine Scope, Context and Job

1. runBlocking can hang your App.

Try out the code, just run it in a simple empty app.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

runBlocking(Dispatchers.Main) {
Log.d("Track", "${Thread.currentThread()}")
Log.d("Track", "$coroutineContext")
}
}

It will hang your App, not able to finish the onCreate function call. Instead, if you run…

--

--