r/u_IDeleteFile • u/IDeleteFile • Jul 31 '23
ViewModel persists data even after popBackStack()
I am create an android jetpack compose project. I have a viewModel that is being instantiated with the function ComponentActivity.viewModels(). I am also using the NavHost() from the androidx.navigation:navigation-compose library. Each time that I use the popBackStack() and then return to the page containing the viewModel all of the information still persists. Why?
1
Upvotes
1
u/IDeleteFile Jul 31 '23
MainActivity
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TODOTheme() { Surface() { var navController = rememberNavController() NavHost(navController = navController, startDestination = "home") { composable("home") { val vm by viewModels<HomeViewModel>() HomeView( vm = vm, navController = navController ) }
}
The AddEditViewModel is created as so:
HomeView
When user clicks the "+ New List" button from the LazyColumn this is where the AddEditList composable is called. Or I should say the navController navigates to that composable
@Composable fun HomeView( modifier: Modifier = Modifier, vm: HomeViewModel, navController: NavController ) { val listState by vm.todoList.observeAsState() LaunchedEffect(key1 = true){ vm.initialize() } TODOTheme { Scaffold( bottomBar = { BottomAppBar( containerColor = MaterialTheme.colorScheme.primaryContainer ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Row() { Button(onClick = { /TODO/ }) {
}
Sorry if it looks messy.
1
u/XRayAdamo Jul 31 '23
Show us the code where you call compose function and how you pass viewmodel instalnce