🐦 Kotlin Intermediate

What is coroutineScope in Kotlin and how does it differ from GlobalScope?

Answer

coroutineScope { } is a suspend function that creates a new scope tied to the current coroutine. It suspends until all its child coroutines complete and participates in structured concurrency — if any child fails, all others are cancelled and the exception propagates to the caller. GlobalScope, on the other hand, is a top-level scope that lives for the entire application lifetime and ignores structured concurrency — coroutines launched in it become orphaned if the component that started them is destroyed, causing leaks. Never use GlobalScope in Android; always use lifecycle-aware scopes like viewModelScope or lifecycleScope.