In Android interviews, this question tests whether you understand lifecycle-aware architecture, dependency management, and separation of concerns.
Explain the difference between ViewModel and AndroidViewModel.
Address these points:
AndroidViewModel exposes Application and what trade-offs that creates.ViewModel with dependency injection over AndroidViewModel.The interviewer expects a practical architectural explanation rather than framework trivia. A strong answer should cover lifecycle behavior, testability, coupling to Android framework classes, and when AndroidViewModel is still acceptable.
ViewModel is a lifecycle-aware class designed to hold UI-related state across configuration changes. It should contain presentation logic and depend on abstractions or injected collaborators rather than Android framework objects.
class UserViewModel(
private val repository: UserRepository
) : ViewModel()
AndroidViewModel is a subclass of ViewModel that receives an Application instance. It exists for cases where application-level context is truly required, but it introduces direct framework coupling into the ViewModel layer.
class UserViewModel(app: Application) : AndroidViewModel(app)
The Application object provides a long-lived context that is safer than holding an Activity or Fragment reference. However, needing context inside a ViewModel is often a design smell because many responsibilities can be pushed into repositories or use cases.
val context = getApplication<Application>().applicationContext
Modern Android apps usually inject dependencies into a plain ViewModel using Hilt, Dagger, or another DI approach. This keeps the ViewModel easier to test and avoids making it responsible for locating framework resources directly.
@HiltViewModel
class UserViewModel @Inject constructor(
private val repository: UserRepository
) : ViewModel()
A ViewModel should manage UI state, not act as a gateway to Android system services or resources. When it depends on Application, responsibilities can become blurred and business logic becomes harder to isolate from the platform.