Mark Murphy
11/01/2024, 4:59 PMViewModel
and does work in onCleared()
. Two questions:
1. BasicViewModel
doesn't seem to offer onCleared()
or an equivalent. How do I know when the viewmodel is going out of scope, so I can do cleanup work there?
2. If I need to stick with Jetpack so I get an onCleared()
, and so therefore should use Ballast's AndroidViewModel
... how are we supposed to handle the CoroutineScope
? We're not supposed to use viewModelScope
, but it is unclear if we are on our own to cancel()
some other CoroutineScope
that we create. Do I just cancel()
it myself in onCleared()
?
Thanks!Casey Brooks
11/01/2024, 9:17 PMBasicViewModel
and AndroidViewModel
, everything that Ballast does is running on a coroutines, which means there isn’t much that Ballast is able to do once that scope gets closed. Coroutines don’t allow much for us to do cleanup once the scope is cancelled, and anything that can be done wouldn’t be able to be done within the normal Ballast processing loop once the coroutineScope has been cancelled. As you mentioned, extending Ballast’s AndroidViewModel
will give you access to overriding the onCleared
, which internally is what cancels its coroutine scope and cleans up the whole VM. And for BasicViewModel
, I’m not entirely sure if this will work, but you can try calling viewModelScope.coroutineContext.job.invokeOnCompletion { }
on the scope passed to the VM. This method is used internally, so I’m not sure if calling that yourself will get overridden or not.Casey Brooks
11/01/2024, 9:23 PM