Android Kotlin Coroutines: Is Using Global Scope An Anti-pattern?

This is rather a question for advise then how to.

I am using viewmodelScope to launch jobs to interact with my database in my ViewModel. Some of these jobs can take long and use might navigate away from the Activity/Fragment while job is on going.

I want job to complete no matter what. Is it acceptable to use GlobalScope in this context?



On first sight GlobalScope looks like a good option to achieve long running operations. But then you'd run into an issue with the Android lifecycle.

Assume you're not bound to it anymore. The moment your global operation is done, you'll unsuspend your callbacks within your Activity or Fragment. Additionally you'll leak these instances as well.

Instead you should consider calling your method within a NonCancellable Job:

withContext(NonCancellable) {

Your code will be canceled just after your long running code completed and cleanup properly.

If your calls are completely unrelated to anything from the Android lifecycle, therefore unscoped, just go for GlobalScope.