After cancelling scope, should I throw away the ob...
# coroutines
m
After cancelling scope, should I throw away the object? For example, in android activity lifecycle, I'd want to have coroutine started on resume and cancelled on paused, but for every lifecycle pass, I'd need a new scope object, correct?
z
Technically you just need a new CoroutineContext that contains a new Job, but if you're following best practice and using the
CoroutineScope
factory function then yes, you'd need a new scope.
m
oh, thanks! That makes sense. Docs could be clearer on that part in
CoroutineScope
section 😄 For factory function are you referring functions like
MainScope()
? I'm using them but still keeping the object in the field for reuse, is this something that should be avoided?
z
I mean the
val scope: CoroutineScope = CoroutineScope(yourContext)
factory function.
👍 1
Which
MainScope()
is closely related to. Keeping scopes in a field like that is fine, even encouraged.
m
right, fyi that is what caused problems for me in the first place. Putting
val scope
in activity or fragment, at least when you want to cancel coroutines on pause or on stop. If the system will use same activity object to go back to on start and on pause then your coroutines will just silently not run 🙂
z
m
If you wish to reuse the
scope
in
onResume()
, then you can instead do
scope.coroutineContext.cancelChildren()
in
onPause()
. This keeps the
scope
active for reuse but still makes sure to cancel any launched coroutines.
👏 1
If you're familiar with RxJava and its `CompositeDisposable`:
scope.cancel()
<->
compositeDisposable.dispose()
scope.coroutineContext.cancelChildren()
<->
compositeDisposable.clear()
m
KTX solves it only partially, they're providing scope that is alive until onDestroy. Thanks Marcelo! That's exactly what I needed
👍 1
a
Recent activity and fragement KTX provide solution for this problem
Copy code
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
someWorkThatOnlyPerformedWHileResumed
}
That method will stop coroutine in case app is on pause and will cancel it properly in case activity is destroyed.
👏 1
d
it will suspend coroutines when activity is paused
a
yes, this is what I meant 😄
👍 1
d
also beware of,
scope.cancelChildren()
It's dangerous if you use channels/actors they will be closed, you'd have to reinstanciate them
👍 1