A common pattern I've seen: Holding onto a job be...
# coroutines
r
A common pattern I've seen: Holding onto a job because you want to cancel the existing job if it's already in progress. Is there a better way to do this?
z
Define “better” - what’s wrong with this pattern?
r
@Zach Klippenstein (he/him) [MOD] I'm basically wondering if there's something that does this kind of pattern for you. So maybe "easier" is a better word
z
Depends a bit on your use case, i think. You could get some of the same logic by using Flow operators (e.g. the
*Latest
) ones. But that only makes sense if you’re dealing with flows as input
r
@Zach Klippenstein (he/him) [MOD] got it. Maybe I'll see if I can write my own thing that will make this easier. i just see this pattern so much
z
i’ve used it myself a couple times. I think it’s actually pretty clean:
Copy code
private var job: Job? = null

job?.cancel()
job = scope.launch { }
It’s very little boilerplate, and make it very clear what’s going on.
2
m
You can define your own CoriutineScope and launch coroutines in the scope. and cancel the scope anytime you want. (This is kind of session)
👍 1
g
You can define your own CoriutineScope and launch coroutines in the scope. and cancel the scope anytime you want
How is this better than keeping reference on Job? I would argue that it worse, there is even higher chance that someone will add one more job to this Scope. Of course it useful if you run multiple jobs on this scope
m
Yes, I agree with you. Then I think I misunderstood @Rechee Jozil's intention. I assumed he has a kind of session (like UI session) and he just want to fire-and-forget the coroutine including the cancellation of it. (In short, bind the lifecycle of a coroutine to the session.) If he want to handle the cancellation manually (Cancel a job at arbitarary moment), I think there is no hope except he just keep the reference (either a job or a scope).