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.
Tests whether you understand lifecycle-scoped sharing and the coupling risks of Activity-backed state. A great answer covers four things in order: first, use activityViewModels or navGraphViewModels to scope to the Activity or nav graph; second, expose observable state like LiveData or StateFlow instead of Fragment references; third, watch for memory retention when the Activity hosts many shared ViewModels; fourth, prefer a parent Fragment or repository if the scope should be narrower than the Activity.
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.