I have two fragments A and B , fragment A has an observer which is working fine. fragment A navigates to fragment B, which has a very similar observer that doesn't run on first call,.. I must navigate back to A then B again ! then after that it is working fine.. if i close the app and open it again same thing happens.
Fragment B :
private val viewModel: WorkOutViewModel by activityViewModels() {
MainViewModelFactory(
(requireActivity().application as WorkOutApp).repository
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.e("AdvanceFragment.kt", " opening advance fragment with ID ::: ${args.workoutId} ")
viewModel.populateAdvanceFragment(2) // this populates the advanceworkout list
viewModel.advanceworkout.observe(viewLifecycleOwner, {
if (it.size == 0) {
Toast.makeText(requireContext(), "edit mode advance fragment ", Toast.LENGTH_LONG)
.show()
return@observe
}
// populate ui
}
}
Data source is Room db query that returns a Flow<List> -- aslivedata()
ViewModel:
var advanceworkout: LiveData<List<WorkOutEntity>> = MutableLiveData<List<WorkOutEntity>>()
fun populateAdvanceFragment(id: Int) {
viewModelScope.launch(Dispatchers.IO) {
advanceworkout = repository.getWorkOut(id).asLiveData()
}}
This fragment is called from another fragment using navigation graph :
Fragment A :
viewModel.simpleworkout.observe(viewLifecycleOwner, {
if (it.size == 0) {
Toast.makeText(requireContext(), "edit mode simple fragment ", Toast.LENGTH_LONG)
.show()
return@observe
}
//populate ui
}
binding.advanceFragmentTv.setOnClickListener {
val action =
SimpleFragmentDirections.actionSimpleFragmentToAdvanceFragment(2)
findNavController().navigate(action)
}
First fragment opens from bottom navigation menu .. hosted in the single activity of this app .
How can I ensure that the observer runs when I navigate to the fragment ? why is it behaving like this anyway?