runBlocking is called on the Android main thread, which freezes the interface while it waits
What it finds
Android runs the callbacks of activities, fragments, services, receivers and views on the main thread, which also draws the screen and handles input. runBlocking there stops the whole interface until the coroutine ends; after a few seconds the system reports the app as not responding. The same holds for functions marked @MainThread, @UiThread or @Composable.
Reported for runBlocking directly in such a function, or in lambdas that run in place such as let or apply, where the function is a known main-thread callback such as onCreate, onViewCreated or onReceive of such a class. A lambda handed to another thread or a later callback, other callbacks, which may run on a worker thread as onHandleIntent does, and previews (@Preview) are left alone. Files that import nothing from Android are left alone.
From the rule's source, run_blocking_on_main.rs.
import android.os.Bundleimport androidx.annotation.MainThreadimport kotlinx.coroutines.runBlocking class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val user = runBlocking { repository.load() }tx0 reports: runBlocking in onCreate of a AppCompatActivity blocks the main thread settings.let { runBlocking { it.save(user) } }tx0 reports: blocks the main thread thread { runBlocking { repository.load() } } executor.execute { runBlocking { repository.load() } } } fun helper() = runBlocking { repository.load() }} class Sync : IntentService("sync") { override fun onHandleIntent(intent: Intent?) { runBlocking { repository.sync() } }} class Monitor : BroadcastReceiver(), VpnCallbacks { override fun onVpnStarted() { runBlocking { repository.sync() } }} @Preview@Composablefun SamplePreview() { val items = runBlocking { repository.load() }} class Push : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { runBlocking { repository.sync() } }} @MainThreadfun refresh() { runBlocking { repository.load() }tx0 reports: runBlocking in a @MainThread function} fun background() { runBlocking { repository.load() }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/kotlin:run-blocking-on-main-thread" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/kotlin:run-blocking-on-main-thread] reason="..."tx0 explain tx0/kotlin:run-blocking-on-main-thread shows the same in the terminal. Found a false positive? Report it.