With viewmodel and fragment ktx, you can host a shared viewmodel between a parent fragment and a child fragment, so instead of having your activity contain the instance of the viewmodel and storing the data until that activity finishes, you can store the viewmodel within the parent fragment, doing so, when you pop the fragment that instantiated the viewmodel, the viewmodel will be cleared
Imports
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
ParentFragment (SharedViewModel host)
class ParentFragment:Fragment() {
private val model: SharedViewModel by viewModels()
}
ChildFragment
class ChildFragment:Fragment(){
private val model: SharedViewModel by viewModels ({requireParentFragment()})
}
So, doing this will host the sharedviewmodel in the parent fragment, and the child fragment depending on that parent fragment will have access to that same instance of the SharedViewModel
and when you pop (aka destroying the fragment) , your onCleared()
method will fire at your viewmodel and that shareviewmodel will be cleared, and also all it's data.
This way, you don't have your MainActivity to contain all the data that fragments share, and you don't need to clear that data each time you leave a fragment that uses the SharedViewModel
Now in alpha, you can pass data between navigations using also a viewmodel that will save the data between navigations, lets say you want to share data between Fragment B and fragment A, now you can do it simply with two lines
https://developer.android.com/guide/navigation/navigation-programmatic#returning_a_result