james04
james04

Reputation: 1920

Get same instance viewModel from nested Fragments

I have a layout which is like that MainActivity has a NavHost with 3 Fragments SitesFragment, GroupsFragment, GalleryFragment

GalleryFragment has a ViewPager with 3 Fragments (Image, Audio, Video)

GalleryFragment has a GalleryViewModel

    private val galleryViewModel: GalleryViewModel by viewModels()

So inside the ImageFragment i want to get the SAME INSTANCE of GalleryViewModel

    private val galleryViewModel: GalleryViewModel by viewModels({ requireParentFragment() })

I tried to get it through the parentFragment but it is not the same instance! How can i do that?

Upvotes: 1

Views: 636

Answers (1)

M.ekici
M.ekici

Reputation: 763

You can use activityViewModels() rather than viewModels() so your view models are provided by the activity hosting your fragments. https://developer.android.com/kotlin/ktx#fragment

Upvotes: 1

Related Questions