I’m using the navigation component with compose an...
# compose
j
I’m using the navigation component with compose and I want to reuse a class instance while the current screen/ navEntry is in the backstack. Basically I want to have viewModels that are not android viewModels and that are retained, which is not supported. I have achieved this through DI scopes (with Koin). To cancel the scope I use this code:
Copy code
navBackStackEntry.lifecycle.addObserver(object: LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            koinScope.close()
        }
    }

})
The problem is that this is run on every recomposition, so I end up having a lot of observers. It works (the scope will be closed when it needs to be) but it is not ideal having several useless observers being called. What can I do to only add an observer the first time?
i
Sounds like you're looking for
onCommit(navBackStackEntry)
which will only run when the inputs (i.e., the
NavBackStackEntry
instance changes (which it doesn't, so this only runs once)
j
Thanks for you answer @Ian Lake. It did not work though. Despite getting the same NavBackStackEntry, the onCommit block is called every time (maybe something is different and equals returns false?). To clarify what I do: I start at screen A, navigate to B, navigate to C, and press back. I have the following inside NavHost:
composable(ScreenA) {…}
composable(ScreenB) {
onCommit(it) {…}
}
composable(ScreenC) {…}
With this navigation flow, the onCommit block is called twice.
i
If you log the
NavBackStackEntry
, are you getting a different instance? Or is it the same instance and there's something wrong with
onCommit
?
j
It is the same instance, I logged it and that’s what surprised me. Does onCommit compare contents (==) or instances (===)?
i
It doesn't matter for
NavBackStackEntry
since it intentionally doesn't override equals (object equality is enough), but what you're seeing is certainly unexpected - any call to
navigate
will create a new instance. Do you mind filing a bug with a reproduction project? https://issuetracker.google.com/issues/new?component=409828&template=1093757
i
Thanks, I've routed it over to the right person. We'll take a look
👍 1