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?
Answer
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
.
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View