...

/

Thread Switching and Callbacks

Thread Switching and Callbacks

Learn about thread switching, problems with thread switching, the callback function, and their uses.

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.

Press + to interact
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 ...