SharedViewModel in Android
Learn how to create SharedViewModel in Android
In Android, SharedViewModel is a useful pattern when sharing data between multiple fragments within the same Activity. When you have multiple fragments within an Activity and you want to share data between them without coupling them tightly, SharedViewModel becomes very effective.
For instance, you can update one fragment based on an action in another fragment, and using a shared ViewModel allows you to do this without directly interacting with each other.
Creating a SharedViewModel:
class SharedVM : ViewModel() {
}You can then access this shared ViewModel from different fragments using the same Activity as the ViewModel owner:
Using it in the 1st Fragment:
class OutcomeSchoolFragment1 : Fragment() {
private lateinit var sharedVM: SharedVM
fun initSharedVM() {
sharedVM = ViewModelProvider(requireActivity()).get(SharedVM::class.java)
}
}Using it in the 2nd Fragment:
class OutcomeSchoolFragment2 : Fragment() {
private lateinit var sharedVM: SharedVM
fun initSharedVM() {
sharedVM = ViewModelProvider(requireActivity()).get(SharedVM::class.java)
}
}Note: Creating the SharedViewModel using the same owner(Activity) is important.
This is how you can create a SharedViewModel in Android.
Prepare for your Android Interview: Android Interview Questions and Answers
Thanks
Amit Shekhar
Founder, Outcome School


