Shared ViewModel in Android: The Best Way to Sync Data Between Activity and Fragments

Table of Contents

If you’ve ever built an Android app with multiple fragments and activities, you’ve probably faced the challenge of keeping data in sync across different parts of your UI. Enter the Shared ViewModel in Android — a modern, robust solution that makes data sharing between your activity and its fragments seamless, efficient, and lifecycle-aware.

Let’s break down what a Shared ViewModel is, why it’s the best way to sync data, and how you can implement it in your own Android projects.

What is a Shared ViewModel in Android?

A Shared ViewModel in Android is simply a ViewModel instance that is scoped to an activity, allowing all fragments within that activity to access and share the same data. This approach leverages the lifecycle-aware nature of ViewModels, ensuring that your data survives configuration changes (like screen rotations) and is always up to date for all observers.

Why Use a Shared ViewModel?

  • Decouples Fragments: Fragments don’t need to know about each other. They communicate through the shared data in the ViewModel, keeping your architecture clean and modular.
  • Lifecycle Awareness: Data persists through configuration changes and is automatically cleaned up when the activity is destroyed.
  • Simplifies Communication: No more messy interfaces or direct fragment references. Everything flows through the Shared ViewModel in Android.
  • Syncs Data Instantly: Any change in the ViewModel is immediately observed by all registered fragments and the activity, ensuring your UI is always up to date.

Common Use Cases

  • Master-Detail Screens: Selecting an item in one fragment updates the details in another.
  • Global UI Changes: A toggle in one fragment affects the UI across the activity.
  • Search and Filters: User input in one fragment updates lists or content in others.

How to Implement a Shared ViewModel in Android

Let’s walk through a practical example: syncing a message between two fragments using a Shared ViewModel.

1. Add Required Dependencies

Make sure you have these in your build.gradle.kts:

Kotlin
implementation ("androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.0")
implementation ("androidx.lifecycle:lifecycle-livedata-ktx:2.6.0")

2. Create the Shared ViewModel

Kotlin
class SharedViewModel : ViewModel() {
    val message = MutableLiveData<String>()
    
    fun sendMessage(text: String) {
        message.value = text
    }
}
  • MutableLiveData holds the data and notifies observers when it changes.
  • sendMessage() updates the value, triggering observers in all fragments and the activity.

3. Access the Shared ViewModel in Fragments

Both fragments access the same ViewModel instance by using the activity as the scope:

Kotlin
// In both fragments
private val sharedViewModel: SharedViewModel by activityViewModels()

This ensures both fragments are observing the same data source.

4. Sending Data from One Fragment

Kotlin
// MessageSenderFragment
buttonSend.setOnClickListener {
    sharedViewModel.sendMessage("Hello from Sender!")
}

5. Receiving Data in Another Fragment

Kotlin
// MessageReceiverFragment
sharedViewModel.message.observe(viewLifecycleOwner) { message ->
    textViewReceiver.text = message
}

Whenever sendMessage() is called, textViewReceiver updates instantly with the new message.

Sharing Data with the Activity

The activity can also observe and update the Shared ViewModel in Android. Just retrieve the ViewModel with:

Kotlin
val sharedViewModel: SharedViewModel by viewModels()

Or, if you want the activity to share the same instance as its fragments, use:

Kotlin
val sharedViewModel: SharedViewModel by activityViewModels()

This lets you coordinate UI changes or data updates across the entire screen, not just between fragments.

Tips and Best Practices

  • Scope Matters: Always use requireActivity() or activityViewModels() to ensure fragments share the same instance. Using this or requireParentFragment() creates a new ViewModel instance, breaking the shared behavior.
  • Keep ViewModels Lean: Store only UI-related data. Avoid holding references to Views or Context to prevent memory leaks.
  • Use LiveData: LiveData ensures updates are only sent to active UI components, preventing crashes from background updates.

Real-World Example: Search Screen

Imagine a search screen with a search bar in the activity and two fragments: one showing clubs, the other showing news. When the user types a query, the activity updates the Shared ViewModel. Both fragments observe the query and update their lists accordingly — no direct communication needed.

Why Shared ViewModel in Android is the Best Solution

  • Simplicity: No need for interfaces, event buses, or manual data passing.
  • Reliability: Data survives configuration changes and is always up to date.
  • Scalability: Add more fragments or features without rewriting communication logic.

Conclusion

The Shared ViewModel in Android is the gold standard for syncing data between activities and fragments. It’s clean, efficient, and leverages the best of Android’s architecture components. Whether you’re building a simple app or a complex UI, adopting Shared ViewModel in Android will make your code more maintainable and your user experience smoother.

Happy Coding..! and may your data always be in sync..!

Skill Up: Software & AI Updates!

Receive our latest insights and updates directly to your inbox

Related Posts

error: Content is protected !!