https://kotlinlang.org logo
#android
Title
# android
m

Martin Nordholts

10/01/2019, 10:22 AM
Let’s say I have an Android
DialogFragment
that uses a
ViewModel
with
viewModelScope
support. In the UI, the user fills in a bunch of data and the click a Submit button which closes the dialog and does a
HTTP POST
of the data. Let’s say I use
Retrofit2
with
suspend
support. I should clearly not use
viewModelScope.launch
to do the
HTTP POST
because it will be cancelled when the UI is closed. Naive as am, I think it would be fine to use
GlobalScope.launch
in this case to do the
HTTP POST
, since I under no circumstances want that
HTTP POST
to be cancelled. Would this be bad style? If yes, what scope should I use instead? Some
CoroutineScope
field in my Android
Application
class perhaps? Let’s ignore edge cases like network failure for now.
d

Dominaezzz

10/01/2019, 10:25 AM
under no circumstances want that
HTTP POST
to be cancelled.
GlobalScope
it is. Since something like that literally can't be scoped.
I think there's too much hesitation around
GlobalScope
. So much so, that sometimes I see code like
CoroutineScope(Dispatchers.Main).launch {}
(which is worse that
GlobalScope
) just so
GlobalScope
isn't directly used.
m

Matej Drobnič

10/02/2019, 7:02 AM
under no circumstances
Be careful to not assume this. Request can be cancelled even if your code is perfect. App can crash, phone can run out of battery, wifi router can go down etc.
m

Martin Nordholts

10/02/2019, 7:06 AM
That is a fair point, although with ‘cancel’ I was in this particular case referring to cancel as in Job.cancel(). Sorry for being unclear. App crashes and battery depletion are of course always a possibility.
I think there’s too much hesitation around
GlobalScope
.
Sorry for reviving an old thread but I think this is important to discuss. It is not strange that there is hesitation around this since Roman himself says so here: https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc
d

Daniel

11/13/2019, 5:58 PM
Why not use work manager?
37 Views