ViewModel & UI State Interview Questions
ARCHITECTURE › Components
What is a ViewModel, and why does it survive configuration changes?
What a strong answer covers: A ViewModel holds and manages UI-related state for a screen. The Activity or Fragment's ViewModelStore is kept across configuration changes (it's retained through the non-config instance mechanism), and ViewModelProvider returns the same instance from it, so state survives rotation. It's cleared, calling onCleared, only when the owner is finished for good.
Why shouldn't a ViewModel hold a reference to an Activity, Fragment, View or Context?
What a strong answer covers: The ViewModel outlives the activity across rotation, so holding the old activity or a view leaks it and its whole view hierarchy, and calls would go to a destroyed UI. If you need resources, use AndroidViewModel's application context sparingly, or better, inject something that wraps it, like a string provider. The UI observes the ViewModel, never the other way round.
How do you pass arguments or dependencies into a ViewModel?
What a strong answer covers: With Hilt, annotate it @HiltViewModel with an @Inject constructor and get it with hiltViewModel() or by viewModels(). Navigation arguments arrive through SavedStateHandle. For runtime values not known at injection, use assisted injection (@AssistedInject with a factory). Without DI, use a ViewModelProvider.Factory or the viewModelFactory { initializer { } } DSL.
What is viewModelScope, and what happens to its coroutines when the ViewModel is cleared?
What a strong answer covers: viewModelScope is a CoroutineScope tied to the ViewModel, using SupervisorJob and Dispatchers.Main.immediate. When the ViewModel is cleared, the scope is cancelled, so all its coroutines stop. That's good for UI-bound work but wrong for work that must finish, like saving a payment, which should go to an application-scoped scope or WorkManager.
What are the common mistakes teams make with ViewModels, and how would you review for them?
What a strong answer covers: Exposing mutable state; holding Context or views; doing work in init that should be lazy or triggered, which also makes tests harder; launching unscoped coroutines (GlobalScope); one huge ViewModel for several screens; passing the ViewModel deep into composables; business logic that belongs in the domain layer; and not handling process death for user input. A strong reviewer checks state ownership, testability and lifecycle.