Is there any difference between this two approaches?
runBlocking {
launch(coroutineDispatcher) {
// job
}
}
GlobalScope.launch(coroutineDispatcher) {
// job
}
Is there any difference between this two approaches?
runBlocking {
launch(coroutineDispatcher) {
// job
}
}
GlobalScope.launch(coroutineDispatcher) {
// job
}
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.
I will try a different explanation without repeating the existing standard answers.
The "coroutine scope" is the boundary where the coroutine exists. The "global scope" exists as long as the application process is running. If you use "GlobalScope.launch()" you create a global coroutine that lives in the application scope.
If you use "runBlocking { launch() }" you create a coroutine that lives in the local block just after runBlocking. That local block will not exit as long as the coroutines in it are alive.