I use Compose Destinations library for navigation (but the question actually applies to any way of navigating). And I want to avoid working with navigation in the composite functions that represent my screens. So I want to get rid of such code in my composable functions:
@RootNavGraph(start = true)
@Destination
@Composable
fun Welcome(
navController: DestinationsNavigator,
viewModel: WelcomeViewModel = hiltViewModel()
) {
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collect { event ->
when (event) {
is WelcomeViewModel.Event.NavigateToProfile -> {
navController.navigate(ProfileDestination)
}
/* other navigation events */
}
}
}
WelcomeView()
}
So my question is: how to Inject navController: DestinationsNavigator
into some class (lets say Navigator
) which will be Injected to my ViewModel
so that I can do navigation directly from ViewModel. Something like this:
@HiltViewModel
class WelcomeViewModel @Inject constructor(
private val navigator: Navigator
) : ViewModel() {
/* some variables */
fun onSomeAction() {
/* do some calculations */
navigator.navigateToProfile(param)
}
/* other functions */
}
I tried search for the solution but didn't found anything.
This is not recommended. But you can follow this approach.