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

Android75

02/29/2024, 9:07 PM
I have a very simple question 😞 I have a complex Screen and ViewModel When screen starts i use this method to load data from repo etc.
Copy code
LaunchedEffect(Unit) {
    viewModel.checkData()
}
Ok.. i change screen with navigation
Copy code
navController.navigate(screen.route)
the problem is when go back with
Copy code
navController.navigateUp()
viewModel reload all data
a

Anum Amin

02/29/2024, 9:24 PM
It is because your composable is composed again. checkData() [reload func] should be called once only when viewmodel is created
a

Android75

02/29/2024, 9:27 PM
but i create viewModel in navigation
Copy code
composable(Destination.XXX.path) {
    val viewModel: MyViewModel = hiltViewModel()
        MyScreen(viewModel)
  
}
if i put checkData inside init() checkData will start before Composable
it;s strange.. i put checkData inside init() and it works
a

Anum Amin

02/29/2024, 9:32 PM
yes, because viewmodel is not destroyed when you come back. UI is created again, but VM is there.
that is one of the main essence of VM in android
2 Views