Hi guys, I am started looking use of navigation li...
# compose
k
Hi guys, I am started looking use of navigation library in compose. I am little bit confused about using navigation component with UI events. What is the use case UI events and navigation component’s? When should we choose which options? Any guidance will be great. Thanks
d
Can you add a little more context to your question, maybe with some code examples for comparison?
k
So should I replace my viewmodel function to pass
navigateUp
?
Copy code
fun sendLoadingState(navigation){
    If ()
       navigateUp(Loading)
    else()
 }
I searched in this stackoverflow and found that
navcontroller
can be inject in viemodel class in there. So it is recommended by the compose team ?
d
No it is not recommended
k
So what is the best approach here ?
d
It is recommended to pass the NavigationController to your screens controller. OR to pass a lambda to call down into the screen.
I will get you the documentation.
Copy code
onNavigateToFriends = { navController.navigate("friendsList") },
Navigation is not a ViewModel concern.
Ideally
ViewModel
fetches, holds and manages the data for the UI to render.
A screen level
@Composable
handles the navigation.
k
Perfect it makes sense to me.
d
Personally I would never follow the advice in the Stack overflow comment you posted.
k
It's true stack overflow is not right everytime
d
I understand the urge to move fast at times. But the time invested in reading as much of the official documentation is time well invested 😉
k
Another point you just mentioned above
@Composable
handles the navigation. I found an article in droidcon. I don't want to refector my business logic code in viewmodel. Can I emit an event there and launch it in something like this example?
Screenshot_20230301-004316.png
d
I see the logic here. It’s acting much like an EventBus that triggers navigation. Generally I bubble up events to the ViewController, Usually the MainActivity, or a Fragment. Otherwise I might wrap my my screen
@Composable
in a controller
@Composable
. Like this:
Copy code
@Composable
fun MyScreen(
onThingClick: () -> Unit,
...
) { 
  MyThing(onClick = onThingClick)
 }

@Composable
fun MyScreenController(
navController: NavController,
  viewModel: MyViewModel = hiltViewModel(),
) {
 
  MyScreen(
    onThingClick = {  
navController.navigate("thing_route" 
    }
  )
}
That said, I could see the EventBus approach working.
k
Perfect I can use it now, thanks for the great guidance 🙏 .