Android75
04/05/2022, 4:11 AMIan Lake
04/05/2022, 4:15 AMAndroid75
04/05/2022, 4:24 AM@Composable
fun NavigationComponent(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = Destination.Splash.path
) {
composable(Destination.Splash.path) {
SplashScreen(navController)
}
composable(Destination.Dashboard.path) {
DashboardScreen(navController)
}
composable(Destination.SectionPage.path+"/{type}") {backStackEntry ->
SectionPage(navController, backStackEntry.arguments?.getString("type"))
}
}
}
Every screen receives navController and has its ViewModel.
ViewModel decides destination, of course.
@Composable
fun SplashScreen(navController: NavHostController) {
val viewModel = hiltViewModel<SplashViewModel>()
var splashScreenState = viewModel.uiState.collectAsState().value
ViewModel uses stateUi to change screen.
@HiltViewModel
class SplashViewModel @Inject constructor() : BaseViewModel() {
val uiState = MutableStateFlow(SplashState())
init {
Handler(Looper.myLooper()!!).postDelayed({
gotoDashBoard()
}, 2000)
}
private fun gotoDashBoard() {
uiSate.value = uiState.value.copy(
navigate = Navigate(true, destination= NavigationItem.Dashboard)
)
}
}
In SplashSreen :
if(splashScreenState.navigate.change){
navController.navigate(splashScreenState.navigate.destination.route)
}
ok.. i have a loop. I see Dashboard screen is recreated continuously.
I put this and works.. but i don’t like it
if(splashScreenState.navigate.change){
splashScreenState.navigate.change= false
navController.navigate(splashScreenState.navigate.destination.route)
}
Android75
04/05/2022, 4:26 AMIan Lake
04/05/2022, 4:30 AMIan Lake
04/05/2022, 4:30 AMIan Lake
04/05/2022, 4:31 AMAndroid75
04/05/2022, 4:42 AMnavigate
inside composition so.. how and where i can put code to change screen? Ok for splashscreen but if in Dashboard has 3 buttons.. if i want follow MVVM, buttons send event to ViewModel and after ViewModel decides destination.. how can i change destination..ildar.i [Android]
04/05/2022, 5:15 AMAndroid75
04/05/2022, 5:40 AMLaunchedEffect(Unit) {
viewModel.someUIState.collect { uiState ->
when(uiState) {
// Same as in the question
}
}
}
Android75
04/05/2022, 7:39 AMAndroid75
04/05/2022, 7:52 AMLaunchedEffect(uiState) {
if(uiState.destination.isNotEmpty()) {
navController.navigate(uiState.destination)
}
}
DisposableEffect(LocalLifecycleOwner.current) {
onDispose {
viewModel.resetState()
}
}
ildar.i [Android]
04/05/2022, 7:57 AMgildor
04/05/2022, 9:39 AMildar.i [Android]
04/05/2022, 9:43 AMgildor
04/05/2022, 9:44 AMAndroid75
04/05/2022, 10:03 AM