KotlinLeaner
01/07/2024, 12:14 AMKotlinLeaner
01/07/2024, 12:15 AM@Composable
fun FunAppNavigation(
viewModel: FunAppViewModel = koinViewModel(),
navController: NavHostController = rememberNavController()
) {
val destination = viewModel.navigationHandler.destination.collectAsState()
LaunchedEffect(Unit) {
viewModel.navigateToScreen()
}
LaunchedEffect(key1 = destination) {
navController.navigate(destination.value.route)
}
SideEffect {
println(">> destination Value $destination")
}
}
KotlinLeaner
01/07/2024, 12:16 AMclass FunAppViewModel(
val navigationHandler: NavigationHandler,
) : BaseViewModel() {
fun navigateToScreen() {
val destination = if (true) {
DeviceRoutes.ScreenTwo
} else {
DeviceRoutes.ScreenOne
}
navigationHandler.navigate(destination)
}
}
KotlinLeaner
01/07/2024, 12:16 AMinterface NavigationHandler {
val destination: StateFlow<DeviceRoutes>
fun navigate(deviceRoutes: DeviceRoutes)
}
class Navigator : NavigationHandler {
private val _destination: MutableStateFlow<DeviceRoutes> =
MutableStateFlow(DeviceRoutes.ScreenOne)
override val destination: StateFlow<DeviceRoutes> = _destination
override fun navigate(deviceRoutes: DeviceRoutes) {
_destination.value = deviceRoutes
}
}
sealed class DeviceRoutes(val route: String) {
object ScreenOne : DeviceRoutes("ScreenOne")
object ScreenTwo : DeviceRoutes("ScreenTwo")
}