whats the best way to have handle navgraph onClick...
# compose
u
whats the best way to have handle navgraph onClick events ? the docs state that lambda functions should be passed to the screen but what if there are a lot of onClick events ?
ProfileScreen(onNavigateToFriends = { navController.navigate("friendsList") })
s
You can pass an enum or sealed interface to a single lambda if you don't want to pass a large number of lambdas to your screen.
Copy code
@Composable
fun ProfileScreen(navigate: (NavigationDestination) -> Unit) { ... }

sealed interface NavigationDestination {
    data object FriendsList : NavigationDestination
    ...
}

ProfileScreen(
    navigate = { destination ->
        when (destination) {
            FriendsList -> navController.navigate("friendsList")
            ...
        }
    }
)
u
Thanks. Is it advisable to have the onclick navgraph handlers in the viewmodel instead ? and pass the MyViewModel::onClick sealed interface?
ProfileScreen(myViewModel::onClick)
s
I don't think it's a good practice to expose your nav controller to your view model.
👍 1
There's a pretty good video about event handling, let me see if I can find it.
There's also an article on medium explaining how handling navigation from a view model is an anti-pattern. https://medium.com/androiddevelopers/viewmodel-one-off-event-antipatterns-16a1da869b95
s
How many are we talking about when you say many onClick events? In my experience so far most screens usually only navigate to a few others, so it's been fine to just have the lambdas as-is. Straightforward, doesn't introduce new types, it's fine. Maybe one or two screens end up with like 5 such lambdas but that's fine imo