Has anyone ran into issues with a viewmodel direct...
# android
c
Has anyone ran into issues with a viewmodel directly invoking a navcontroller? The handoff for navigation between a fragment and viewmodel is not at all elegant so I'm thinking about just injecting the navcontroller into the viewmodel but I'm having a hard time finding references that support that idea
t
the NavHostFragment creates the NavController with the context present in onCreate so I would expect that you wouldn't want to hold a hard reference to a nav controller unless you created it manually with the application context as the argument. otherwise memory leaks would be a thing
c
Gotcha, using the navcomponent with a viewmodel and livedata feels quite awkward
t
view model ends up being a super leaky abstraction due to it rafting across points in the fragtivity lifecycle. so even though the attempt is to break away from it, you still have to be innately aware of the lifecycle. live data to me is, pointless for lack of a better word... so many other reactive api's already in the wild at that point, which when used properly make live data pointless. even without magic things like auto dispose, it is straightforward to respect the lifecycle
all of which is say, how far does it go before it is easier to just build the solution you need for your app rather than trying to shoe horn your app into the constraints of a handful of jetpack aac libs
c
Yeah, I find myself hitting limitations of LiveData fairly often.
I want the ViewModel to determine what destination a user should go to given an action... But since LiveData just stores the last value, navigating backwards LiveData will still have the previous destination as its value so it re-navigates back to that destination 😂
t
live data stateful by default right? so in that case it would need to be an event not a state
c
Yeah that's a really good point
s
You could also use a shared view model scoped to a graph to handle the navigation. Such a VM would live through the graph lifecycle and hold the right screen in a Livedata
c
I worry that would create more problems than it'd solve. The other ViewModels would need reference to that ViewModel so they can pass navigation arguments to it.
I landed on just creating an interface that exposes the events, ends up being fairly simple
o
Hey @Cody Engel, I also faced this issue initially. Wanted to use LiveData to for exposing events to the view, but LiveData being made for representing a last value, makes it not a fit for events. What would be a really nice option that goes with coroutines is
Flow
. So I would have something like
Copy code
interface ViewModel {

    val navigateToChatScreenEvents: Flow<NavigateToChatScreenEvent>

    object NavigateToChatScreenEvent

}