Can a Dialog have a view model in android?

Viewed 2308

I need to do an API call from a Dialog. Do I need to go back to the fragment for doing so, or is there any way to refer to the fragment view model?

3 Answers

You can try with this:

  1. Use interface, implement it in fragment so you have callback funtion.

  2. Pass high ordered function, declare it like this in dialog:

    var click: (() -> Unit)? = null;

    Then you can set it from fragment when you instantiate your dialog.

  3. Use shared view model, for example make view model in your activity and then you can access it from every fragment or dialog like this:

(requireActivity() as MainActivity).viewModel

Like this you can set value in view model variable (liveData often) inside your dialog and observe changes in fragment

Yes, it is possible and I was able to do that because class DialogFragment extends Fragment. So I added a view model just like any other fragment.

enter image description here

like below where BaseDialog class extends DialogFragment

enter image description here

I think you can pass a high ordered function to dialog and handle it in fragment using viewModel inside.

Related