18

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.

kkkkk
  • 572
  • 1
  • 10
  • 21
  • You can check out here https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing – Uuu Uuu Aug 03 '20 at 08:21
  • 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. – kkkkk Aug 03 '20 at 08:28
  • you show dialog and dialogFragment at the same time? – Công Hải Aug 03 '20 at 08:33
  • Yes. I show fragment and over it I show dialog fragment. I run same request to update UI in fragment and dialogFragment. – kkkkk Aug 03 '20 at 08:35
  • and you want to share between fragment and dialogFragment right? – Công Hải Aug 03 '20 at 08:36
  • Yes. Only between them. – kkkkk Aug 03 '20 at 08:37
  • Check my answer – Công Hải Aug 03 '20 at 08:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219116/discussion-between-kkkkk-and-cong-hi). – kkkkk Aug 03 '20 at 08:57

1 Answers1

32
  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() })
WindRider
  • 11,958
  • 6
  • 50
  • 57
Công Hải
  • 4,961
  • 3
  • 14
  • 20