Search⌘ K
AI Features

Thread Switching and Callbacks

Understand the limitations of thread switching and callbacks in Kotlin coroutines. Learn why frequent thread switching leads to memory leaks and complexity, and how callbacks, while nonblocking, complicate cancellation and code readability. Discover why these traditional methods struggle with parallelization and control flow in asynchronous tasks.

Thread switching

We could solve the problem (from the previous lesson) by switching threads, first to a thread that can be blocked and then to the main thread.

Kotlin
fun onCreate() {
thread {
val news = getNewsFromApi()
val sortedNews = news
.sortedByDescending { it.publishedAt }
runOnUiThread {
view.showNews(sortedNews)
}
}
}

Problems with thread switching

Thread switching like this can still be found in some applications, but it's known for being problematic for several reasons:

  • There is no mechanism to cancel these threads, so we often face memory leaks.

  • Making that many threads is costly.

  • Frequently switching threads is confusing and hard to manage. ...