How do you guys handle coroutine scopes in Fragmen...
# android
n
How do you guys handle coroutine scopes in Fragments? I find with most of my tasks that cancelling on pause is the most logical choice, as they are usually started when the view is created. But if I cancel the scope, I can't re-launch tasks on it upon resuming.
m
Do you have a viewmodel for the fragment? My viewmodels implement
CoroutineScope
, and that way they can continue doing their work through
onPause
. The fragments are updated through
LiveData
Moving logic into a viewmodel has the side-effect of being unit-testable as well
n
I don't necessarily want my coroutine to continue to do their work while paused. If I do, then I use the ViewModel
l
I create a scope in onStart that is automatically cancelled in onStop with the
createScope
function of self-made Splitties Lifecycle Coroutines library.
n
@louiscad what if, for example, you need to transition to another fragment after making a suspending call? Then you have to be in a scope that is canceled onPause, right? (to avoid duplicate transitions, ie multiple "go to other screen" button presses)
l
@nwh I use suspending functions to handle clicks, so I can't have duplicate button presses problems. You can easily do the same by having a coroutine waiting for a click, then adding a
delay(arbitraryDelay)
after it in a
while (isActive)
loop. To await for a click, you can find to extensions for
View
in Splitties Views Coroutines:
awaitOneClick()
and
visibleUntilClicked { … }
.
n
Interesting, I'll take a look. Seems like for every problem I have, there is a Splitties library that fixes it
l
For every problem I have, I think about if it could/should be a library 😉