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

Kulwinder Singh

04/06/2018, 1:17 PM
so my updated function is good i think
g

gildor

04/06/2018, 2:17 PM
Your function do not respect Android components lifecycle. If you want to use it on android would be better to cancel coroutines on destroy (or other lifecycle event)
Also, I actually don't see why do you need such function. For coroutine code just use delay, for non coroutine you can use postDelay (
UI
dispatcher actually uses it under the hood) or just start coroutine with required dispatcher
k

Kulwinder Singh

04/06/2018, 3:54 PM
as you said that Cancel coroutine at onDestroy ,does this means coroutines are running after doing its task ?
like after calling my function it creates Corutine and does it will exists forever?
t

travis

04/06/2018, 5:05 PM
Your coroutine will end in your code sample, but only after the delay you specified. So, for example, if your delay is set to the equivalent of 10 minutes, then user navigates away from that activity, if you don't cancel the coroutine then your
work.invoke
will still execute after the 10 minutes are up.
k

Kulwinder Singh

04/07/2018, 2:29 AM
ok i understood ,thanks
g

gildor

04/07/2018, 3:47 AM
Coroutine itself will be collected by GC when work (everything inside coroutine) is finished, but only after that. If you cancel coroutine it also cancels nested coroutines (if coroutine uses the same job, or just supports cancellation like
delay
), also canceled coroutine automatically prevent invocation of next suspend function call
3 Views