- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 146字
- 2021-08-05 10:46:49
What happens when the UI is blocked
It's a good opportunity to take a practical approach in order to further understand why the UI thread of an Android application should not be blocked. Let's add this simple block of code to MainActivity, and run the application again:
override fun onResume() {
super.onResume()
Thread.sleep(5000)
}
This will block the UI thread for five seconds. If you run the application again, you will notice how the screen is completely white during those five seconds. This would be dreadful for the user of the application.
Not only should the UI thread never be blocked, it should also not perform tasks that are CPU-intensive because this would result in a similar experience for the user. In short, you should only use the UI thread to create and update views, anything in between should be done in a background thread.