Is it sufficient to use `viewModelScope` for datab...
# coroutines
f
Is it sufficient to use 
viewModelScope
 for database operations (Room)? Theoretically, it could be canceled prematurely if we leave the app before the operation is done (although I don't know if it's possible to leave the app that fast), right? Do you do anything specific to prevent this?
g
Depends what kind semantics you need exactly You can use abstract direct access to database with repository which uses app-level scope, or just Global scope, to prevent operation cancellation when view model is cleared This approach allows still suspend until operation is completed
But I wouldn't use global scope in View model itself, it may cause leak if used incorrectly
f
Thank you. But what if we close the last screen in the app? Globalscope seems to still finish the execution even if I delay it by 10 seconds (I haven't tried a bigger delay). How does this work? Does Globalscope outlive the process?
g
No, of course not, system may shutdown your app with all threads
To be 100% safe you need foreground service
f
alright, thank you
g
But usually it's overkill for for sql operations, but if you are doing some very big operation (like populating database with thousands records) it may be a reasonable thing
f
yea that makes sense
for normal short operations you probably don't need a service
g
Right, also system is usually not so strict, will not shutdown app for some time But it still may be a case in some situations, you can emulate with developer options if set limit of background processes to 0, but it much more strict than what you have on practice
f
But still, Globalscope and NonCancelable seem to outlive the process for a while
because they run even if I close the app and put a 10s delay into the coroutine
whereas viewmodelScope doesn't
g
Yes, sure, it will work until app process is not killed by the system, which in normal condition may be long time (but there also other cpu and io restrictions on modern versions of Android)