Unexpected UI freeze when navigating between Fragments with Jetpack Navigation and Shared ViewModel in Android 14
I'm building a feature where I'm experiencing a important UI freeze when navigating between two Fragments that share a ViewModel using Jetpack Navigation in my Android 14 application. The question occurs specifically when the first Fragment contains a RecyclerView with a large dataset, and I am using a DiffUtil-based adapter. The scenario seems to arise when I attempt to navigate away from the first Fragment to the second while the RecyclerView is still performing animations on data changes. I have tried to implement the ViewModel with LiveData to handle the dataset and notify the UI of changes, but it doesn't seem to help. Here's a simplified version of my setup: ```kotlin class SharedViewModel : ViewModel() { private val _items = MutableLiveData<List<MyItem>>() val items: LiveData<List<MyItem>> get() = _items fun updateItems(newItems: List<MyItem>) { _items.value = newItems } } class FirstFragment : Fragment() { private lateinit var viewModel: SharedViewModel private lateinit var adapter: MyAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) adapter = MyAdapter() // RecyclerView setup recyclerView.adapter = adapter viewModel.items.observe(viewLifecycleOwner) { items -> adapter.submitList(items) // This is where the freeze occurs } return inflater.inflate(R.layout.fragment_first, container, false) } } class SecondFragment : Fragment() { // Implementation for the second fragment } ``` I've verified that the data update process is efficient and that I'm using `DiffUtil` correctly. Despite this, when I navigate to the `SecondFragment`, the UI becomes unresponsive for a few seconds. The Logcat doesn't show any errors, just some warnings about the RecyclerView's view recycling process. I've also tried using `viewModelScope.launch` to perform data updates off the main thread, but the question continues. Has anyone faced something similar or have suggestions on how to improve the performance or handle navigation in this scenario? Could it be related to the Fragment lifecycle or the way I'm handling LiveData updates?