简体   繁体   中英

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 .

To quote Roman Elizarov, the Kotlin libraries team lead who works on Coroutines, on this topic :

There is hardly ever reason to use GlobalScope in an application that is based on Kotlin coroutines.

If, as you say, you want the "job to complete no matter what" keep in mind that everything has a scope. Whether it's a fragment, activity or application, everything comes to an end, eventually. So the better solution is to use structured concurrency and launch your database job from the scope associated with its work.

It sounds like that's the activity in your case. However, if your UI cannot prevent the user from leaving the activity before work is done, and it is critical that the job always completes, then you probably need more than just coroutines. Consider scheduling your long-running work with WorkManager , instead.

Either way, try to avoid GlobalScope since it is not the right solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM