Home / Companies / Stream / Blog / Post Details
Content Deep Dive

Exercise Caution When Using runBlocking on Android

Blog post from Stream

Post Details
Company
Date Published
Author
Jaewoong E.
Word Count
2,753
Language
English
Hacker News Points
-
Summary

Kotlin, now a preferred language for Android development, offers significant features like built-in support for asynchronous and non-blocking programming through coroutines, with tools such as launch, async, and runBlocking. While runBlocking is commonly used in Kotlin's documentation to initiate coroutines, it should be used cautiously in Android development since it blocks the current thread until the coroutine's execution is complete, risking UI freezes or an Application Not Responding (ANR) when used on the main thread. The article explores the internal workings of runBlocking, demonstrating through examples how it blocks the thread and the potential deadlocks that may occur when misused, particularly with Dispatchers.Main. It emphasizes that runBlocking is more appropriately used in unit testing and controlled synchronization tasks on I/O threads where blocking is acceptable. Additionally, the article suggests alternatives like Job.join() for synchronization purposes and highlights the importance of understanding coroutines' internal mechanisms to leverage their full potential in Android development.