Also, if I use the same view model for multiple ro...
# compose-android
d
Also, if I use the same view model for multiple routes, how do I get the appropriate route from the savedStateHandle in the viewModel? Use
toRoute()
multiple times and catch each one until the right one is found, or maybe make them inherit from a base sealed interface and use
toRoute()
on that (is that supported)?
2
j
I ran into this in my app as well. I know that calling
toRoute()
with a sealed interface type when passing in the concrete implementation for the route doesn’t work out of the box. You can maybe get it to work by providing your own
NavType
impl. I ended up refactoring these screens to actually be a single route by moving them out into their own nav graph so they can be routed to from multiple other nav graphs.
s
I'd say just don't use the same VM for all of them. Have a dedicated VM per-screen, and then extract all the logic of them to one shared class. In the VM, do the ssh.toRoute<>() and pass the necessary data to that shared class. This should make your life so much simpler tbh
1
d
Yeah, well, I'm trying to refactor an app I didn't code... so I'm trying to do things step by step, breaking the least amount of functionality as possible until I manage to understand why they did things the way they did...
🙌🏿 1
s
Delegating should then be a great way, since you get the opportunity to split things up in more readable chunks. How all of our VMs look like for example is:
Copy code
internal class FooViewModel(
  private val someInteraction: SomeUseCase,
  private val savedStateHandle: SavedStateHandle,
) : MoleculeViewModel<FooEvent, FooUiState>(
    FooUiState.Loading,
    FooPresenter(someInput = savedStateHandle.toRoute<>().someInput, someInteraction = someInteraction),
  )
and the presenter does all the work. That's what I'd do here, so each screen has one VM and grabs its own SavedStateHandle, but you share the logic somewhere else.
d
Yeah, that could be a nice idea, thanks! I'm still wondering if they really thought twice before making those four routes... they all have more or less the same structure... it might be that later I'll discover that all I needed was one path! That's really why I was avoiding the separation until I get to know the code-base better. I might not have a choice though... Btw, you defined that MoleculeViewModel? I'm a bit curious how you structured your code to use it... I'd guess FooPresenter is the composable with all the logic?