How is the correct way to use DialogFragment in MVVM architecture?

Viewed 1739

I am trying to use DialogFragment in MVVM architecture but I cannot find the answers to some questions.

  1. Should I use the @AndroidEntryPoint annotion? Like this:

    @AndroidEntryPoint
    class MyDialogFragment(): DialogFragment() {
    
    }
    
  2. How should I provide the viewModel? Should DialogFragment have its own viewModel? Or is it better to use Fragment's viewModel? Like this:

    val viewModel: FragmentViewModel by viewModels()
    

    OR

    val viewModel: DialogFragmentViewModel by viewModels()
    
  3. How should I communicate with the fragment I have called DialogFragment for?

1 Answers

You should annotate the DialogFragment with @AndroidEntryPoint that way and don't forget to add @Assisted private val savedStateHandle: SavedStateHandle in your viewModel constractor , the second question is personal preferences, some will use the main fragments ViewModel but if you plan on using the DialogFragment in multiple places you could have that have its own viewmodel, and as for communication you can pass data using events you can have a look at https://developer.android.com/guide/topics/ui/dialogs#PassingEvents

Related