There are different ways of launching a coroutine in Kotlin. I found a couple of examples where GlobalScope and CoroutineScope are used. But the latter one is being created directly when launching a coroutine:
Using
GlobalScope:fun loadConfiguration() { GlobalScope.launch(Dispatchers.Main) { val config = fetchConfigFromServer() // network request updateConfiguration(config) } }Using
CoroutineScopeinstances, created directly when launching a coroutine:fun loadConfiguration() { CoroutineScope(Dispatchers.Main).launch { val config = fetchConfigFromServer() // network request updateConfiguration(config) } }
In this case is there a difference between these two approaches?
Doesn't the second case violate the principle of structured concurrency?
Actually both cases violate it equally, because they have pretty much the exact same semantics. All the warnings against using
GlobalScope.launchthat you may have encountered, apply toCoroutineScope().launchjust the same. A slight difference is that the latter is entirely pointless, whereas the former at least has some legitimate use cases.Writing
CoroutineScope().launchinstead ofGlobalScope.launchobscures the intent and consequences, as well as creates a needless object every time.I think the
CoroutineScope().launchidiom came into being solely because it circumvented the warnings you get forGlobalScope.launch.