How do you share a ViewModel across multiple Fragments?

Tests ViewModel scoping and Fragment communication. A strong answer names activityViewModels or navGraphViewModels, warns about Activity memory retention and hidden coupling, and suggests a parent Fragment or data flow alternative.
WHAT THIS TESTS: Your understanding of ViewModel scoping APIs, lifecycle ownership, and safe inter-Fragment communication. The interviewer wants to see that you know how to share state without creating memory leaks or tight coupling between UI controllers.
A GOOD ANSWER COVERS: First, name the exact APIs: activityViewModels in Kotlin or ViewModelProvider with the Activity as ViewModelStoreOwner to scope the instance to the Activity lifecycle. Second, mention navGraphViewModels or ViewModelProvider with a NavBackStackEntry when the shared scope should match a navigation subgraph rather than the entire Activity. Third, describe the observable state pattern: the ViewModel exposes LiveData, StateFlow, or a data stream, and Fragments collect it without holding direct references to each other. Fourth, list concrete risks: the Activity retains the ViewModel until it finishes, so heavy state or many shared ViewModels increase memory pressure; Fragments become implicitly coupled to the same backing state, making independent testing and reuse harder; and improper scoping can outlive the intended Fragment pair if the Activity survives. Fifth, mention alternatives: a parent Fragment scope via by viewModels with a shared owner, or a repository layer with application scope, depending on the actual data lifetime needed.
COMMON WRONG ANSWERS: Using a singleton or static instance to share data bypasses lifecycle awareness and leaks across configuration changes. Creating a new ViewModel in each Fragment and trying to sync them manually with callbacks or interfaces creates fragile two-way coupling. Holding a direct reference to another Fragment inside the ViewModel defeats the purpose of the pattern and crashes after configuration changes.
LIKELY FOLLOW-UPS: How would you test a shared ViewModel in isolation? When would you choose a navigation graph scope over an Activity scope? How do you clear shared state when the user leaves a specific flow but the Activity remains alive?
ONE CONCRETE EXAMPLE: In a checkout flow with three Fragments for address, payment, and review, a CheckoutViewModel scoped to the checkout navigation graph via navGraphViewModels holds order state. The address Fragment updates a shipping address field, the review Fragment collects the same field as StateFlow, and the ViewModel is automatically cleared when the user pops the checkout graph, even though the host Activity continues running.
Source: developer.android.com
Read the original → developer.android.com
- #android
- #viewmodel
- #fragments
- #lifecycle
- #architecture
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.