Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
runBlocking in Kotlin Coroutines with Example
Next article icon

runBlocking in Kotlin Coroutines with Example

Last Updated : 10 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite:

  • Kotlin Coroutines on Android
  • Suspend Function In Kotlin Coroutines

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)

Log output

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)

Log output

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)

Log output

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.


Next Article
runBlocking in Kotlin Coroutines with Example

L

lavishgarg26
Improve
Article Tags :
  • Kotlin
  • Android

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences