Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How are viewmodels shared between fragments in android?


Asked by Khalil Carson on Nov 29, 2021 Android



TL;DR: We can pass parameters to our ViewModel, use it as a data holder, also to share data between Fragments, and to persist its state across process recreation. This is part of a multi-part series regarding Advanced ViewModels on Android. This post focuses on how our ViewModel can be shared between Fragments. Other posts in this series:
Furthermore,
ViewModel as the bridge between the View and the Model. TL;DR: We can pass parameters to our ViewModel, use it as a data holder, also to share data between Fragments, and to persist its state across process recreation. This is part of a multi-part series regarding Advanced ViewModels on Android.
Keeping this in consideration, Data sharing between Fragments. Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity. Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.
Next,
Starting with Fragment 1.3.0-alpha04 , each FragmentManager implements FragmentResultOwner . This means that a FragmentManager can act as a central store for fragment results.
And,
When working with child fragments, your parent fragment and its child fragments might need to share data with each other. To share data between these fragments, use the parent fragment as the ViewModel scope. override fun onViewCreated(view: View, savedInstanceState: Bundle?)