DEV Community

Cover image for Shared ViewModel: A modern way to share data between android fragments and activities
Sandeep Satpute
Sandeep Satpute

Posted on

Shared ViewModel: A modern way to share data between android fragments and activities

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

  1. Bundle while replacing the fragment/activity
  2. By using interface
  3. 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.
Image description

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.

Image description

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") }
    }


Enter fullscreen mode Exit fullscreen mode

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
        })
    }


Enter fullscreen mode Exit fullscreen mode

Precaution: Create SharedViewModel using the same owner.

Git Repository Link

Conclusion
We learned about Shared ViewModel in Android to communicate with other fragments. Hope you enjoyed this blog.

Happy Learning

Top comments (0)