Is there any difference between this two approaches?
runBlocking {
launch(coroutineDispatcher) {
// job
}
}
GlobalScope.launch(coroutineDispatcher) {
// job
}
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With