0
0
Kotlinprogramming~5 mins

RunBlocking for bridging in Kotlin

Choose your learning style9 modes available
Introduction

RunBlocking helps you run asynchronous code in a simple, blocking way. It lets you wait for tasks to finish before moving on.

When you want to call suspend functions from regular code that doesn't support coroutines.
When writing simple main functions or tests that need to wait for coroutine results.
When you want to bridge between blocking and non-blocking code safely.
When you need to run coroutine code but your environment requires blocking calls.
Syntax
Kotlin
runBlocking {
    // coroutine code here
}

runBlocking creates a coroutine that blocks the current thread until its work is done.

Use it mainly in main functions or tests, not in regular app code to avoid freezing the UI.

Examples
This runs a simple coroutine that prints a message and blocks main until done.
Kotlin
fun main() = runBlocking {
    println("Hello from runBlocking!")
}
Here, runBlocking waits for a suspend function to finish and then prints the result.
Kotlin
runBlocking {
    val result = someSuspendFunction()
    println("Result: $result")
}
Sample Program

This program uses runBlocking to wait for a 1-second delay inside a coroutine before printing the end message.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Start")
    delay(1000L) // pretend to do some work
    println("End after 1 second")
}
OutputSuccess
Important Notes

runBlocking should not be used inside UI threads in apps because it blocks the thread.

It is great for quick tests or main functions where you want to wait for coroutine work.

Summary

runBlocking bridges blocking and coroutine code by blocking the current thread until coroutine finishes.

Use it mainly in main functions or tests, not in UI or performance-critical code.