Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin coroutines GlobalScope.launch vs runBlocking

Is there any difference between this two approaches?

runBlocking {
   launch(coroutineDispatcher) {
      // job
   }
}
GlobalScope.launch(coroutineDispatcher) {
   // job
}
like image 799
silent-box Avatar asked Feb 23 '19 13:02

silent-box


People also ask

What is the difference between launch and async in Kotlin coroutines?

The difference is that launch returns a Job and does not carry any resulting value, while async returns a Deferred — a light-weight non-blocking future that represents a promise to provide a result later. You can use .

When should I use runBlocking?

runBlocking() - use when you need to bridge regular and suspending code in synchronous way, by blocking the thread. Just don't overuse it. Don't treat runBlocking() as a quick fix for calling suspend functions. Always think if instead you shouldn't propagate suspending to the caller.

What is GlobalScope launch?

Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely. Active coroutines launched in GlobalScope do not keep the process alive. They are like daemon threads.

What is runBlocking in coroutines?

Definition of runBlocking() functionRuns 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.


1 Answers

runBlocking runs new coroutine and blocks current thread interruptibly until its completion. This function should not be used from 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.

// line 1
runBlocking {
   // line 2
   launch(coroutineDispatcher) {
      // line 3
   }
   // line 4
}
// line 5
someFunction()

In case of using runBlocking lines of code will be executed in the next order:

line 1
line 2
line 4
line 3
line 5 // this line will be executed after coroutine is finished

Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely. Another use of the global scope is operators running in Dispatchers.Unconfined, which don't have any job associated with them. Application code usually should use application-defined CoroutineScope, using async or launch on the instance of GlobalScope is highly discouraged.

// line 1
GlobalScope.launch(coroutineDispatcher) {
   // line 2
}
// line 3
someFunction()

In case of using GlobalScope.launch lines of code will be executed in the next order:

line 1
line 3
line 2

Thus runBlocking blocks current thread until its completion, GlobalScope.launch doesn't.

like image 169
Sergey Avatar answered Nov 02 '22 07:11

Sergey