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

KotlinLeaner

02/27/2023, 10:09 PM
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

dewildte

02/27/2023, 11:13 PM
Can you add a little more context to your question, maybe with some code examples for comparison?
k

KotlinLeaner

03/01/2023, 12:24 AM
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

dewildte

03/01/2023, 12:30 AM
No it is not recommended
k

KotlinLeaner

03/01/2023, 12:31 AM
So what is the best approach here ?
d

dewildte

03/01/2023, 12:31 AM
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

KotlinLeaner

03/01/2023, 12:36 AM
Perfect it makes sense to me.
d

dewildte

03/01/2023, 12:36 AM
Personally I would never follow the advice in the Stack overflow comment you posted.
k

KotlinLeaner

03/01/2023, 12:38 AM
It's true stack overflow is not right everytime
d

dewildte

03/01/2023, 12:38 AM
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

KotlinLeaner

03/01/2023, 12:42 AM
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

dewildte

03/01/2023, 12:55 AM
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

KotlinLeaner

03/01/2023, 12:59 AM
Perfect I can use it now, thanks for the great guidance 🙏 .
5 Views