https://kotlinlang.org logo
Title
n

nwh

02/26/2019, 9:56 PM
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

matt tighe

02/26/2019, 11:28 PM
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

nwh

02/26/2019, 11:50 PM
I don't necessarily want my coroutine to continue to do their work while paused. If I do, then I use the ViewModel
l

louiscad

02/27/2019, 1:48 AM
I create a scope in onStart that is automatically cancelled in onStop with the
createScope
function of self-made Splitties Lifecycle Coroutines library.
n

nwh

02/27/2019, 2:42 AM
@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

louiscad

02/27/2019, 3:13 AM
@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

nwh

02/27/2019, 6:05 PM
Interesting, I'll take a look. Seems like for every problem I have, there is a Splitties library that fixes it
l

louiscad

02/27/2019, 7:46 PM
For every problem I have, I think about if it could/should be a library 😉