Junior — Middle
At what point in the application architecture is the ViewModel usually instantiated?
sobes.tech AI
Answer from AI
An instance of ViewModel is usually created in a UI component, such as an Activity or Fragment. This is done using ViewModelProvider, which ensures the preservation of the ViewModel's state during configuration changes, such as screen rotations.
Example of creating a ViewModel in a Fragment in Kotlin:
class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Use viewModel to update UI
}
}