Replace Navigation Action with popBackStack
Currently after creating a new Todo in AddEditTaskFragment the code uses a navigation component action to get back to the TasksFragment and passing a message (Task added). This leads to current TaskFragment object and its TasksViewModel to be destroyed. It's not ideal since we are observing database for new todos and there's no need to start over the process of retrieving all the todos.
Instead the code can use SavedStateHandle for setting a message and popping the back stack to get back to TasksFragment which is listening to backStackEntry's LiveData for any changes.
Proposed Improvement Replace navigation action with:
findNavController().popBackStack() – to go back without destroying TasksFragment.
Use SavedStateHandle to pass a result/message back.
This way:
TasksFragment is retained in memory.
It listens for updates via getBackStackEntry() and its SavedStateHandle.
Performance improves, and state/data remains intact.
Example Fix Implementation In AddEditTaskFragment.kt:
// Instead of navigate(R.id.action_addEditTaskFragment_to_tasksFragment) findNavController().previousBackStackEntry?.savedStateHandle?.set("task_result", "Task added") findNavController().popBackStack() In TasksFragment.kt:
val navController = findNavController() val savedStateHandle = navController.currentBackStackEntry?.savedStateHandle savedStateHandle?.getLiveData<String>("task_result")?.observe(viewLifecycleOwner) { result -> showMessage(result) // show SnackBar or update UI savedStateHandle.remove<String>("task_result") // optional cleanup } Benefits Prevents fragment recreation
Keeps existing LiveData observers intact
Better user experience (no UI flicker or reloading)
Follows recommended Single-Activity architecture and state-safe navigation patterns