Search code examples
androidandroid-fragmentsmvvmandroid-dialogfragmentandroid-viewmodel

Android share ViewModel between fragment and dialog fragment?


How to share same viewModel between dialog and dialogFragment? I know that viewModel can be shared in activity scope. But it is too big scope for me.

 private val model: SharedViewModel by activityViewModels()

Unfortunately I don't have in a project navigation component.


Solution

    1. Use childFragmentManager to show DialogFragment

    2. Declare shared ViewModel inside Fragment by

    private val sharedViewModel: YourViewModel by viewModels()
    
    1. Inside DialogFragment declare ViewModel by
    private val sharedViewModel: YourViewModel by viewModels(ownerProducer = { requireParentFragment() })