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

igorvd

05/17/2018, 2:45 PM
If I'm using
android architecture components
with
LiveData
, is still necessary to cancel my coroutines in the
onDestroy
lifecycle method ?
u

540grunkspin

05/17/2018, 2:52 PM
I guess there are two parts to this: 1. Memory leaks. 2. Cancelations. If you reference something like a view or an activity context in the coroutine i think you have to in order to prevent a memory leak. If the job that the coroutine is irrelevant if the UI goes away then you might wan’t to cancel that task for performance reasons.
But i think that if the only thing you do is report results to a LiveData object then you should be fine without canceling the task.
l

louiscad

05/17/2018, 3:31 PM
That all depends on how, when and what about your coroutines launch and work
i

igorvd

05/17/2018, 4:41 PM
I can see the point of performance, to avoid unnecessary work if the UI is going away. But it gets trick because of the
onDestroy
may be called on configuration changes, and so, if I cancel a coroutine that was used to start an async operation, I kinda miss the lifecycle aware part of the LiveData, because it will restart my work - The part of memory leaks I understand and yeah, it's always something relevant. But I guess it's not possible because I use the livedata to update the UI. I asked because I'm not sure if I'm missing something here. Thanks guys!
l

louiscad

05/18/2018, 7:13 AM
@igorvd Do your work in a
ViewModel
, and cancel your parent job in its
onCleared
method
i

igorvd

05/18/2018, 1:15 PM
@louiscad Hmm thats sounds reasonable. But the job is start in the UI components (Activity, fragment), how to get access to them without referencing the view? Do you have an example for that? Thanks man !
l

louiscad

05/18/2018, 1:17 PM
@igorvd Your UI component calls a method from your ViewModel that launches the job
i

igorvd

05/18/2018, 1:35 PM
normally I do in the activity:
launch(UI, parent = Job) { viewModel.doSomething() }
, on the ViewModel I just use
async
or
withContext
. The
async
I can associate with a parent job too, but the withContext I can't. Do you have an opnion about that?
l

louiscad

05/18/2018, 1:42 PM
If you don't need to stay in the activity, make a regular method in your ViewModel that will launch the coroutine, and call this regular method in your Activity/Fragment
i

igorvd

05/18/2018, 4:30 PM
so I would call the
launch(UI)
on the viewModel?
l

louiscad

05/19/2018, 11:46 PM
@igorvd Exactly, that's what I do in such cases
You can also have an
actor
in your
ViewModel
i

igorvd

05/21/2018, 12:08 PM
do you have an example of that? But I'll give it a try to understand it better
l

louiscad

05/21/2018, 1:57 PM
@igorvd No open source example I have at hand at the moment, but I'll try to make one when I have some time for it
👍🏼 1
2 Views