Android share ViewModel between fragment and dialog fragment?
Asked Answered
A

1

20

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.

Antichrist answered 3/8, 2020 at 7:48 Comment(8)
You can check out here developer.android.com/topic/libraries/architecture/…Trigonal
Yeah I exactly used this source. This line in question is even from this page. The problem is that my fragment shows product details and I have multiple products and I need to clean my liveData manually. And I have only one activity, so I don't needed this viewModel all the time. Only when user enters the details page.Antichrist
you show dialog and dialogFragment at the same time?Eliath
Yes. I show fragment and over it I show dialog fragment. I run same request to update UI in fragment and dialogFragment.Antichrist
and you want to share between fragment and dialogFragment right?Eliath
Yes. Only between them.Antichrist
Check my answerEliath
Let us continue this discussion in chat.Antichrist
E
35
  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() })
Elevenses answered 3/8, 2020 at 8:41 Comment(5)
Really appreciated. Nicely described.Haemagglutinate
Is there an updated version where we show it using android navigation?Aldas
@Aldas you can use the same by viewModels delegate because the navigation component uses the childFragmentManager as well.Pinter
what about the opposite case, get viewModel for a fragment that opened by dialoge. so i need viewmodel between parent (dialoge), and fragment [child]?Simsar
hmmm this didn't work. app crashes when dialog fragment tries to get the vmPlaymate

© 2022 - 2024 — McMap. All rights reserved.