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

koufa

11/26/2017, 9:42 AM
Or how to you handle the
lifecycle
with
coroutines
? How do you avoid leaking an
activity
? Is
job.cancel()
on
onDestroy
enough to avoid memory leaks?
l

louiscad

11/27/2017, 8:27 AM
If you launch coroutines
Job
inside your
ViewModel
, you can assign the
launch
call to a private nullable
Job
property and make the last line of your coroutine set your it back to
null
(unless you need to or may launch your coroutine multiple times, before the first one is completed). Then, in your `ViewModel`'s
onCleared
method, you can safe call (with a
?
)
cancel
on your
Job
property. Of course, the coroutine will be effectively cancelled only if a cancellable suspend method encounters the cancel signal. Also, don't forget to catch the
CancellationException
inside your coroutine.