parentfragment scope for viewmodel android code example

Example: define parent fragment viewmodel

Using Fragment-ktx libr in your app you can get viewModel as below in your app-> build.gradle

 implementation 'androidx.fragment:fragment-ktx:1.1.0'
// get ViewModel in ParentFragment as

 private val viewModel: DemoViewModel by viewModels()
// get same instance of ViewModel in ChildFragment as

 private val viewModel: DemoViewModel by viewModels(
    ownerProducer = { requireParentFragment() }
)

Tags:

Misc Example