Sobes.tech
Junior — Middle

Millised tagajärjed võivad tekkida, kui kutsutakse otse ViewModel konstruktor, et luua selle eksemplar?

sobes.tech AI

Vastus AI-lt

Directly calling the ViewModel constructor (for example, via new ViewModel()) in Android results in the ViewModel's lifecycle not being managed by the system. As a consequence:

  • The ViewModel will not be preserved during screen rotations or Activity/Fragment recreations.
  • The main advantage of ViewModel — state preservation — is lost.
  • Memory leaks may occur if the ViewModel holds references to the UI.

The correct way to create a ViewModel is to use ViewModelProvider, which ensures proper lifecycle management:

val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

This ensures the reuse of a single ViewModel instance within the component's lifecycle.