Hello! I have a project with Jetpack Navigation Co...
# compose-android
o
Hello! I have a project with Jetpack Navigation Compose and Android ViewModels. So most of my screens have designated NavBackStackEntry (which is also a ViewModelStoreOwner) and in terms of ViewModel's lifecycle (if I create it with
hiltViewModel
) everything works as expected: when I navigate back, NavBackStackEntry is removed, ViewModelStoreOwner is cleared and my ViewModel becomes destroyed. The problem is when I want to reuse my
MediaScreen
inside another, let's say
Profile
screen, for example inside a Pager or just embed in Column -
MediaScreen
is being created in scope of parent
ProfileScreen
. It means that
MediaScreen
will be cleared only when I leave
ProfileScreen
. Instead of that I want to have some control over this
MediaViewModel
lifecycle to destroy it when
MediaScreen
leaves composition (Pager page removed, or it was a part of ModalBottomSheet) I've managed to achieve it by wrapping
MediaScreen
into
NavHost
with single route but it looks like overhead just to reuse one screen. I'm looking for some composable function like
@Composable fun <VM> composeViewModel(): VM
which creates a new ViewModel instance as
hiltViewModel()
does but clears the ViewModel and remove it from ViewModelStore when this function leaves composition,
And another issue of
hiltViewModel
- I can't embed
MediaScreen
twice on the same screen and create two separate instances of
MediaViewModel
because the class is the same and it doesn't allow to pass some tag/id/key to distinguish them
c
I think the whole viewModel scoped to a composable with compose-nav and hilt is only for composable destinations. So if I'm understanding your problem correctly, I wouldn't reuse MediaScreen directly inside of another app as MediaScreen is a destination. I'd create some other composable inside of MediaScreen and then use that composable (with no ref to the VM) inside of your ProfileScreen.