Shared ViewModel: A modern way to share data between android fragments and activities
Sandeep Satpute
Posted on July 10, 2022
In android development, developer multiple time come across a situation where needs to share the data between fragments and activities. So there are multiple ways to share the data between fragments and activities such as
- Bundle while replacing the fragment/activity
- By using interface
- Shared viewModel
Let's start with shared viewModel which is the simplest way of sharing the data between fragments/activities.
What is viewModel and responsibility of viewModel
The ViewModel class is designed to store and manage UI-related data in a lifecycle-conscious way. ViewModel class acts as an interface between Fragments to sharing data.
ViewModel Life cycle helps us to hold the data and keep that live even if fragment is replaced.
Shared viewModel
The shared view model is the normal view model only but the data holding behaviour and life cycle of view model help us to make it shared view model.
As per life cycle data is available even if caller fragment get destroy and we can get that data for other fragments.
Example
Sender Fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
button.setOnClickListener { model.sendMessage("Techno Learning") }
}
Receiver Fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
model.message.observe(viewLifecycleOwner, Observer {
textViewReceiver.text = it
})
}
Precaution: Create SharedViewModel using the same owner.
Conclusion
We learned about Shared ViewModel in Android to communicate with other fragments. Hope you enjoyed this blog.
Happy Learning
Posted on July 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 10, 2022