https://kotlinlang.org logo
#coroutines
Title
# coroutines
u

uli

09/26/2019, 7:34 PM
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

withoutclass

09/26/2019, 7:37 PM
u

uli

09/26/2019, 7:55 PM
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

louiscad

09/26/2019, 7:57 PM
What you want is something like
createScope
here, or just that: https://github.com/LouisCAD/Splitties/tree/master/modules/lifecycle-coroutines
u

uli

09/26/2019, 8:15 PM
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

louiscad

09/26/2019, 8:29 PM
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

uli

09/26/2019, 8:30 PM
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

withoutclass

09/26/2019, 8:48 PM
you can also use
cancelChildren
and keep the root job around iirc
2
u

uli

09/26/2019, 8:50 PM
Interesting. Didn't think of it yet. But then I'd have to keep the job around
l

louiscad

09/26/2019, 8:54 PM
cancelChildren would let coroutines started after onStop run before onStart is called again, and until the second onStop call though
👍 1
4 Views