Hi, I see a lot of examples for attaching `Corouti...
# coroutines
u
Hi, I see a lot of examples for attaching
CoroutineScope
to Android lifecycles with a pattern like that:
Copy code
class UiLifecycleScope : CoroutineScope, LifecycleObserver {

    private lateinit var job: Job
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onCreate() {
        job = Job()
    }
Do you guys see any reason for constructing the context with a getter, creating a new context every time. How about making the scope
var
?
Copy code
override lateinit var coroutineContext: CoroutineContext
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onCreate() {
        coroutineContext = Dispatchers.Main + Job()
    }
w
u
Sure. But all this does not work if you want to cancel in onStop. Then your activity might get restarted but your scope is cancelled. That's why you have to inject a new Job()
l
What you want is something like
createScope
here, or just that: https://github.com/LouisCAD/Splitties/tree/master/modules/lifecycle-coroutines
u
Thanks @louiscad. I'll take a look. But this does not answer the question. I am not looking for a solution but for clarification. The pattern I described is everywhere on Google but seems to be second best. That's what I am trying to understand
l
You should call your job/scope startedJob/Scope for explicitness.
Creating a new context/scope each time doesn't seem good to me. I'd just create a scope on each onStart call, and do what I need there, possibly launching child coroutines.
u
I'd rather say rootJob. After I call cancel it is no longer started
@louiscad thanks, creating a new context in onStart is what I thought. Just too bad about every example out there goes with a context getter
w
you can also use
cancelChildren
and keep the root job around iirc
2
u
Interesting. Didn't think of it yet. But then I'd have to keep the job around
l
cancelChildren would let coroutines started after onStop run before onStart is called again, and until the second onStop call though
👍 1