If I'm using `android architecture components` wit...
# coroutines
i
If I'm using
android architecture components
with
LiveData
, is still necessary to cancel my coroutines in the
onDestroy
lifecycle method ?
u
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
That all depends on how, when and what about your coroutines launch and work
i
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
@igorvd Do your work in a
ViewModel
, and cancel your parent job in its
onCleared
method
i
@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
@igorvd Your UI component calls a method from your ViewModel that launches the job
i
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
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
so I would call the
launch(UI)
on the viewModel?
l
@igorvd Exactly, that's what I do in such cases
You can also have an
actor
in your
ViewModel
i
do you have an example of that? But I'll give it a try to understand it better
l
@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