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

Rechee Jozil

03/01/2021, 10:44 PM
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

Zach Klippenstein (he/him) [MOD]

03/01/2021, 10:56 PM
Define “better” - what’s wrong with this pattern?
r

Rechee Jozil

03/01/2021, 10:58 PM
@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

Zach Klippenstein (he/him) [MOD]

03/01/2021, 10:59 PM
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

Rechee Jozil

03/01/2021, 11:16 PM
@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

Zach Klippenstein (he/him) [MOD]

03/01/2021, 11:24 PM
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

myungpyo.shim

03/01/2021, 11:25 PM
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

gildor

03/02/2021, 1:59 AM
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

myungpyo.shim

03/02/2021, 2:51 AM
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).
3 Views