Search code examples
androidkotlinandroid-fragmentsandroid-livedataandroid-dialogfragment

How to notice when DialogFragment is dismissed in my Fragment?


I'm navigating from a Fragment to a DialogFragment. What I want to do is notice when this DialogFragment is dismissed in my Fragment to do something.

I'm trying doing this updating a LiveData but for some reason,when the DialogFragment is closed, the LiveData value is never true like I'm trying to do.

MyFragment:

private val myViewModel: MyViewModel by viewModel() //Using Koin
btn1.setOnClickListener{
   findNavController().navigate(R.id.my_dialog_fragment)
}

myViewModel.dialogFragmentIsClosed.observe(viewLifecycleOwner){isClosed->
if(isClosed)
  //do something
}

MyViewModel:

private val _dialogFragmentIsClosed = MutableLiveData(false)
val dialogFragmentIsClosed: LiveData<Boolean> get() = _dialogFragmentIsClosed
fun isDialogFragmentClosed(closed:Boolean){
  _dialogFragmentIsClosed.postValue(closed)
}

DialogFragment:

private val myViewModel: MyViewModel by viewModel() //Using Koin

override fun onDismiss(dialog:DialogInterface){
  myViewModel.isDialogFragmentClosed(true)
  val bundle = bundleOf(Pair("argBoolean",true))
  findNavController().navigate(R.id.my_fragment,bundle)
}

Solution

  • First of all, your DialogFragment and MyFragment are not sharing the same instance of MyViewModel.

    To achieve your goal, you should check this document: https://developer.android.com/guide/navigation/navigation-programmatic#additional_considerations

    You will open DialogFragment from MyFragment, then observer the result from DialogFragment.

    If you want to share the same instance of ViewModel, change to use activityViewModel() ( instead of using viewModel() )