Search code examples
javaandroidandroid-viewmodelandroid-architecture-components

How ViewModel is persisted on configuration change


Looking at the ViewModel documentation, it says:

In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel.

How is the ViewModel not destroyed if the activity referencing it is destroyed? and how is it reconnected once we create a new activity?


Solution

  • Behind the scenes a retained fragment is used. A retained fragment has its state retained across Activity re-creation (such as from a configuration change).

    See "Architecture Components Introduction" talk from Google IO 2017, where Yigit Boyar talks about ViewModel.