https://kotlinlang.org logo
Title
a

Android75

04/04/2022, 2:37 AM
I have a strange problem. I use navigation
fun NavigationComponent(navController: NavHostController) {
    NavHost(
        navController = navController,
        startDestination = Destination.Splash.path
    ) {
        composable(Destination.Splash.path) {
            Log.i("test"," Splash screen" )
            SplashScreen(navController)
        }
        composable(Destination.Dashboard.path) {
            Log.i("test"," Dashboard screen" )
            DashboardScreen(navController)
        }
        composable(Destination.SectionPage.path+"/{type}") {backStackEntry ->
            Log.i("test"," Sectionpage  screen" )
            SectionPage(navController, backStackEntry.arguments?.getString("type"))

        }
    }
}
I send navController to page.
@Composable
fun SplashScreen(navController: NavHostController?) {

    val viewModel: SplashViewModel= viewModel()
   viewModel.setNavigationController(navController )
I save navController inside ViewModel so i can change page. it works but navigate call screen 2 o 3 time.. i have this log I: Splash screen I: Splash screen I: Splash screen I: Dashboard screen I: Dashboard screen
i

Ian Lake

04/04/2022, 5:37 AM
There's a lot going on in this code, so starting from the beginning, keeping a reference to the NavController in a
ViewModel
is going to be a memory leak, something we just talked about: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1648769777776709
Secondly, you should be using the splash screen APIs for a splash screen, that should never be the start destination of your graph as per the Principles of Navigation
Third, you should never be doing any side effects as part of composition - this particularly includes navigating (your composable should be able to rerun 1,000s of time over) as cases like animation will cause you to recompose on every frame: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1628623578239700?thread_ts=1628620645.223300&cid=CJLTWPH7S
a

Android75

04/04/2022, 11:45 AM
Ok thanks so...ViewModel uses uiState to invoke navigate using NavController parameter of screen
I created a hilt Module.
@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Singleton
    @Provides
    fun providesNavigationManager() = NavigationManager()
}
class NavigationManager @Inject constructor(){

var navController: NavController?=null
}
In Activity inject NavigationManager and set navController so i can use in ViewModel by inject manager
i

Ian Lake

04/05/2022, 5:15 AM
I'd suggest reading the side effects docs - navigating is definitely a side effect: https://developer.android.com/jetpack/compose/side-effects