how to popBackStack with popUpTo ?
# compose
h
how to popBackStack with popUpTo ?
f
h
thanks for links I already checked them. When I am doing navcontroller.popBackStack to navigate back the viewmodel is kept in the memory. I want to kill that viewmodel
f
What viewmodel? Viewmodel of the screen you pop to or from which you pop?
h
I will give example. I am in the chat screen and want to go back to chat list screen. Both of them have viewmodels. So when I go back to chat list and open another chat I am getting messages from previous chats. Their viewmodels are still alive. I want to just kill chat screen viewmodel as soon as I go back to chat list
navController.popBackStack doesn't do that
f
I see, so you navigate ChatList -> Chat where you inject your VM using composable function
getViewModel()
. Then you call
navController.popBackStack()
which navigates you back to ChatList. When you navigate again to different Chat destination, you get the same VM instance? Can you verify that it is the same instance and not just VM that fetches the same data?
h
it's not same VM instance. if I open let's say 5 chat it creates 5 viewmodels. so When I open chat 6 I will get every message that was sent in previous 5 chats. I just want to kill the viewmodel as soon as I leave the Chat screen so when I open new chat viewmodel will be freshly created
f
Well if it's different instance, than the previous ViewModel has been killed, no? Than I don't really understand the problem
h
it's not getting killed. I don't know why. each time it creates different instance and that instance lives in memory
f
Are you sure you don't keep a reference to the Viewmodel somewhere? And can you check that
onCleared
is called in the VM?
h
onCleared
is not getting called when I navigate back
f
Weird, what dependency injection are you using? Koin?
h
yes
oh god
I declared it with single
🤦
changed to viewModel but still is not getting cleared
f
There you go 😄 That's weird that you got a different instance actually.
h
wait emulator is shown offline for some reason let me check again
no luck 😕
f
Well... I don't what else to check 🤷
h
but somehow it works now 😕
🤔
hahah worked clean build
f
🤦‍♂️
h
thank you sooo much @Filip Wiesner you saved me tons of headaches
f
No worries 👌 Just next time you have to ask something more specific and it's better to write what you've tried so far. Seeing question like "_how to popBackStack with popUpTo?_" is really annoying because you will have to ask a lot of questions first to find the problem.
h
Thanks for your patience. I surely will next time 😌
420 Views