Junior — Middle
What type of scope would you choose for the ViewModel in your project?
sobes.tech AI
Answer from AI
For ViewModel in an Android project, the scope is usually chosen to match the lifecycle of the UI component it is associated with:
- ViewModelScope, linked to the Activity — if the ViewModel should live as long as the Activity and survive configuration changes like screen rotations.
- ViewModelScope, linked to the Fragment — if the ViewModel is only needed for a specific fragment.
This allows the ViewModel to preserve UI state and data during configuration changes, while releasing resources when the UI component is destroyed.
Example of creating a ViewModel with an Activity scope:
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
where this is the Activity or Fragment defining the scope.