Vikas Pandey
Vikas Pandey

Reputation: 1235

how does suspend function not block the main thread?

A coroutine started on Dispatchers.Main won't block the main thread while suspended. what does this mean? so when suspend function started on main thread when has some lines which takes longer, does it automatically assign to new thread? this is confusing?

Upvotes: 7

Views: 2048

Answers (2)

Asdinesh
Asdinesh

Reputation: 183

A suspended function will run on a thread like any normal function, but it will not block the main thread when it switches to another thread.

A normal function when switches from the main thread to a background thread, it has to block the main thread because it does not know from where to continue after execution.

    ...
    val result = getResult()  // This blocks the main thread due to join
    use(result);

fun getResult(): String {
    var result: String = ""
    val t = Thread(Runnable {
        ...
        result = "woohoo"
    })
    t.start()
    t.join()  // Main thread is waiting for the result to return it
    return result
}

But when a suspended function switches thread, it will not block the main (previous) thread, because it knows from where to continue after execution.

launch(Dispatchers.Main) {
    ...
    val result = getResult()  // This will not block the main thread
    use(result)
}

suspend fun getResult(): String = withContext(Dispatchers.IO) {
    ...
    "woohoo"
}

Upvotes: 7

Animesh Sahu
Animesh Sahu

Reputation: 8106

Dispatchers.Main is a CoroutineContext which dispatches the coroutine into main thread but when the coroutine itself suspends, i.e. by changing context or thread or some other reason then the "main thread becomes free" and the Continuation object under the hood is responsible for continuing the execution afterwards.

Since there is no task running on main thread upon suspension, it is free and able to take another task by the context (Dispatcher), and hence is documented as it is not-blocked.

Upvotes: 1

Related Questions