I am attempting to migrate an older project to Bal...
# ballast
m
I am attempting to migrate an older project to Ballast. The project used a Jetpack
ViewModel
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!
c
In both
BasicViewModel
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.
thank you color 1
Additionally, VMs go out of scope in response to UI events, so you might look into hooking into the relevant UI Lifecycle callback for the cleanup, rather than relying on the VM itself. VMs are best used when they’re ephemeral, meaning they can basically be created or destroyed at-will without needing specific lifecycle management. Alternatively, adjust your navigation logic so the cleanup is handled explicitly by the VM before dispatching the navigation request, or structure your data layer so the things that would normally need to be cleaned up in response to the VM aren’t so dependent on the application/UI lifecycle.