runBlocking in Kotlin Coroutines with Example
Last Updated :
10 Sep, 2021
Prerequisite:
As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI and many more things. As the delay function is a suspend function it has to be called from the coroutine or another suspend function.
Definition of runBlocking() function
According to official documentation, the runBlocking() function may be defined as:
runBlocking is a coroutine function. By not providing any context, it will get run on the main thread.Runs a new coroutine and blocks the current thread interruptible until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
Kotlin
// sample program in android studio to demonstrate coroutines
package com.example.gfgcoroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
val TAG:String="Main Activity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
GlobalScope.launch(Dispatchers.Main) {
delay(3000)
Log.d(TAG,"User is in the Global Scope ")
Toast.makeText(applicationContext,"User is in the Global Scope ",Toast.LENGTH_SHORT).show()
}
Log.d(TAG,"User is not in the Global Scope ")
Toast.makeText(applicationContext,"User is not in the Global Scope ",Toast.LENGTH_SHORT).show()
}
}
Log Output:
Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)
As it can be seen in the log-output that the "User is in the Global Scope" gets printed after the Log of "User is not in the Global Scope" which shows that the GlobalScope start a coroutine, which does not block the main thread, and the other operations can be performed while the delay time get's over. But when someone wants to call only the suspend function and do not need the coroutine behavior, one can call the suspend function from the runBlocking. So when one wants to call any suspend functions such as delay() and do not care about the asynchronous nature, one can use the runBlocking function. The difference between the calling the suspend function from the GlobalScope.launch{ } and calling the suspend function (eg delay()) from runBlocking{ } is that runBlocking will block the main thread or the thread in which it is used and GlobalScope.launch{ } will not block the main thread, in this case, UI operations can be performed while the thread is delayed.
Another use-case of runBlocking is for testing of the JUnit, in which one needs to access the suspend function from within the test function. One case also uses the runBlocking in order to learn the coroutines in-depth in order to figure out how they work behind the scenes. Let's see from the examples below how runBlocking actually works:
Kotlin
package com.example.gfgcoroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity()
{
val TAG="Main Activity"
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG,"Before run-blocking")
runBlocking
{
Log.d(TAG,"just entered into the runBlocking ")
delay(5000)
Log.d(TAG,"start of the run-blocking")
Log.d(TAG,"End of the runBlocking")
}
Log.d(TAG,"after the run blocking")
}
}
Log Output:
Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)
The Round oval circle in the above log-output shows the timestamps in which the log output is being printed. It can be clearly seen that when the "just entered into the runBlocking" the delay of 5 sec is encountered, so other operations can not be performed and have to wait for 5 seconds. The Log statement "after the run blocking" which is outside of the runBlocking function too, has to wait for the whole runBlocking function to finish its work. Let's take another example and try to learn how runBlocking works and how different coroutines can be launched within it.
Kotlin
package com.example.gfgcoroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity()
{
val TAG="Main Activity"
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG,"Before run-blocking")
runBlocking
{
Log.d(TAG,"just entered into the runBlocking ")
delay(5000)
launch(Dispatchers.IO)
{
delay(3000L)
Log.d(TAG,"Finished to coroutine 1")
}
launch(Dispatchers.IO)
{
delay(3000L)
Log.d(TAG,"Finished to coroutine 2")
}
Log.d(TAG,"start of the run-blocking")
Log.d(TAG,"End of the runBlocking")
}
Log.d(TAG,"after the run blocking")
GlobalScope.launch
{
Log.d(TAG,"Logging in the globalScope")
}
}
}
Log Output:
Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)
It can be seen in the above log-output that both GlobalScope and launch will execute after the delay of runBlocking. As both the coroutine which are launched within runBlocking with launch function will be executed within the same thread, it seems like both the coroutine are running in parallel, but it is not possible since both are running in the same thread, but they are running in an asynchronous manner. So it can be said that users should use coroutine runBlocking only when the user wants to do a JUnit test or want to call only the suspend functions.
Similar Reads
Room Database with Kotlin Coroutines in Android
This project will be used for the implementation phase. If you have not yet completed the project, you should do so and then return. To keep things simple, the project employs a basic MVVM architecture. The complete code for the implementation mentioned in this blog can be found in the project itsel
3 min read
withContext in Kotlin Coroutines
Prerequisite: Kotlin Coroutines on AndroidLaunch vs Async in Kotlin Coroutines It is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is
3 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Kotlin Flow in Android with Example
Kotlin Flow is a tool that helps developers work with data that changes over time like search results, live updates, or user input. Itâs part of Kotlinâs coroutines, which are used for writing code that doesnât block the app while waiting for something to finish, like a network call or a file to loa
8 min read
Launch vs Async in Kotlin Coroutines
The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used
4 min read
Exception Handling in Kotlin Coroutines
Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
7 min read
Scopes in Kotlin Coroutines
Scope in Kotlin's coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. Kotlin CoroutinesScope is a term well used in the referred for the interface used for defining the Scope(lifetime and context
6 min read
use Keyword in Kotlin with Example
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Kotlin Function Variations With Examples
While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
3 min read
Dispatchers in Kotlin Coroutines
Prerequisite: Kotlin Coroutines on Android It is known that coroutines are always started in a specific context, and that context describes in which threads the coroutine will be started in. In general, we can start the coroutine using GlobalScope without passing any parameters to it, this is done w
3 min read