https://kotlinlang.org logo
#compose
Title
# compose
u

0xf1f1

03/10/2024, 7:44 PM
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

Sean Proctor

03/10/2024, 8:52 PM
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

0xf1f1

03/10/2024, 9:04 PM
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

Sean Proctor

03/10/2024, 9:06 PM
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

Stylianos Gakis

03/10/2024, 11:56 PM
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