0
0
Kotlinprogramming~10 mins

RunBlocking for bridging in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - RunBlocking for bridging
Start main thread
Enter runBlocking
Start coroutine inside runBlocking
Coroutine runs and suspends if needed
Coroutine completes
Exit runBlocking
Resume main thread
runBlocking starts a coroutine and blocks the main thread until it finishes, bridging regular and coroutine code.
Execution Sample
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Start")
    delay(1000L)
    println("End")
}
This code runs a coroutine that prints 'Start', waits 1 second, then prints 'End', blocking main thread until done.
Execution Table
StepActionCoroutine StateMain Thread StateOutput
1Enter runBlockingStartedBlocked waiting
2Print "Start"RunningBlockedStart
3Call delay(1000L)Suspended (waiting 1s)Blocked
4Delay completesResumedBlocked
5Print "End"RunningBlockedEnd
6Coroutine completesCompletedUnblocked
7Exit runBlockingN/ARunning
💡 Coroutine finished, runBlocking unblocks main thread and exits.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
Coroutine StateNot startedRunningSuspendedRunningCompleted
Main Thread StateRunningBlockedBlockedBlockedRunning
Key Moments - 2 Insights
Why does the main thread wait inside runBlocking?
Because runBlocking blocks the main thread until the coroutine inside it completes, as shown in execution_table rows 1 to 6.
What happens during delay inside runBlocking?
The coroutine suspends (row 3), but the main thread stays blocked until the coroutine resumes and finishes (rows 4-6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the coroutine state at Step 3?
ARunning
BCompleted
CSuspended
DNot started
💡 Hint
Check the 'Coroutine State' column at Step 3 in the execution_table.
At which step does the main thread become unblocked?
AStep 4
BStep 6
CStep 5
DStep 7
💡 Hint
Look at the 'Main Thread State' column in execution_table rows 5 and 6.
If delay was removed, how would the execution_table change?
ACoroutine would never suspend
BMain thread would block longer
COutput would be delayed
DCoroutine would stay suspended
💡 Hint
Without delay, coroutine runs straight through without suspension (see Step 3 suspension).
Concept Snapshot
runBlocking { ... } runs a coroutine and blocks the current thread until it finishes.
It bridges regular blocking code with coroutines.
Inside runBlocking, coroutine code can suspend (like delay).
Main thread waits until coroutine completes.
Useful for main functions or tests needing coroutine results synchronously.
Full Transcript
runBlocking starts by blocking the main thread and launching a coroutine. The coroutine runs and can suspend, for example during delay. While suspended, the main thread stays blocked. When the coroutine finishes, runBlocking unblocks the main thread and exits. This lets normal blocking code wait for coroutine results safely.