Hi guys! There are scopes, like `ViewModelScope` f...
# coroutines
u
Hi guys! There are scopes, like
ViewModelScope
from
AAC
, which works best for most of simple use cases, but when you want to cancel the job whose lifecycle is very specific, then there is a place for discussion. Suppose an operation should be run starting from
onStart()
call until there is a
onStop()
call. What would you suggest as good practice here to control this operation’s lifecycle? I started by creating custom scope, inside which this operation would run, then i realised, that after cancellation this scope can’t be re-used. Then I thought that creating a new scope every time
onStart()
is called is a bad idea (or not?). So I switched to a nullable variable holding a reference to a
Job
created after
launch { ... }
in
onStart()
, which I cancel in
onStop()
. Seems normal, but what if you want to cancel a lot of different jobs between `onStart()`/()`onStop()` calls? I might want a strange thing to do: having a scope, which, when you cancel it, cancel all its children job, but could be reset to allow new coroutines to run. Perhaps, I do not understand properly which logic stands behind not allowing to re-use cancelled scope. Thanks!
e
Simplest solution is what you said:
lifecycleScope.launch {}
a bunch of `Job`s in
onStart
and cancel them in
onStop
. To keep track of all jobs at once, just use a class property
private val jobs = mutableListOf<Job>()
and simply add jobs to it:
jobs += lifecycleScope.launch {}
. in
onStop
just
jobs.forEach { it.cancel() }
(which could be a nice extension on
Collection<Job>
)
👍 1
And probably you should also
jobs.clear()
in
onStop