Junior — Middle
What are the risks associated with using GlobalScope in Kotlin, and why is it considered unsafe?
sobes.tech AI
Answer from AI
Using GlobalScope in Kotlin is considered unsafe due to the following risks:
-
Lack of lifecycle control: coroutines launched in GlobalScope live until the application terminates, which can lead to memory leaks or tasks running after components (e.g., Activity) are destroyed.
-
Difficulties with cancellation: it is hard to cancel a coroutine because it is not tied to a specific lifecycle or context.
-
Potential synchronization errors: due to the lack of lifecycle constraints, race conditions or incorrect states may occur.
Therefore, it is recommended to use more local scopes, such as lifecycleScope in Android, which automatically cancel coroutines when the component is destroyed, ensuring safety and manageability.