I have created one chatsheetfragment(Bottomsheetdialogfragment). Whenever I open it I'm calling all the chats and binding in RecyclerView. So, my problem is the chat sheet is always reloading from onCreate() which eventually results refreshing the fragment every time. how to stop it.
And I'm using viewmodel using dagger-hilt . Viewmodel instance is also creating every time.
Tried opening as singleton instance but not worked and now I'm opening like below
private fun chatButton() {
binding.chatIv.setOnClickListener {
ChatSheetFragment().show(
supportFragmentManager,
ChatSheetFragment::class.java.simpleName
)
}
}
With
ChatSheetFragment(), a brand new fragment is getting created and therefore a brand newViewModelin case that you bind thisViewModelto that fragment.This can be solved by binding that
ChatSheetFragmentto the parent activity/fragmentViewModelthat can host the updated list.So, in short:
Change the
ViewModelin theChatSheetFragmentto either the parent fragment/activity (according to your desgin):i.e., instead of
ViewModelProvider(this)[MyChatViewModel::class.java]you'd replacethiswithrequireParentFragment()orrequireActivity()and replaceMyChatViewModelwith the one of the parent fragment/activity.Move the list logic that you want to maintain from the chat fragment
ViewModelto the parentViewModel.Another solution is not to create a brand new fragment with
ChatSheetFragment()and just show the existing one; but not sure if that can affect the performance to keep it alive while you don't need it.Edit:
This is right; calling
dismiss()or even setting the BottomSheetBehavior state toSTATE_HIDDENwill destroy the fragment.But there is a workaround to just hide the decorView of the dialogFragment window whenever you want to hide the chat fragment like the following:
But you need to handle the situations when the DialogFragment can hide; here is a couple ones:
Customize the dialog in
onCreateDialog():Whenever you want to show the fragment again; just show its dialog without re-instantiating it as described above