ViewModel's purpose is to retain data on life cycle events and configuration changes.
But for certain configuration changes, like locale change, I would like to get a fresh instance of viewModel. How can I force recreation?
class HomeActivity : AppCompatActivity() {
var viewModelFactory: ViewModelProvider.Factory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// How to get new instance on locale change?
var viewModel = ViewModelProviders.of(this, viewModelFactory)
.get(HomeViewModel::class.java)
}
}
The ViewModel class allows data to survive configuration changes such as screen rotations. Usually, one of the first things we find out when learning Android development is that activities get re-created after configuration changes.
The ViewModel remains in memory until the Lifecycle it's scoped to goes away permanently: in the case of an activity, when it finishes, while in the case of a fragment, when it's detached. Figure 1 illustrates the various lifecycle states of an activity as it undergoes a rotation and then is finished.
There are few lifecycle aware android architecture components: ViewModel: Helps to create, store and retrieve data and communicates with other components belonging to the same lifecycle. Lifecycle Owner: It's an interface implemented by activity and fragment, to observe changes to the lifecycle of owners.
ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. FYI: You can use ViewModel to preserve UI state only during a configuration change, nothing else as explained perfectly in this official doc.
Answering my own question :)
I had the chance to speak with Yigit Boyar (lead for Architecture Components) on Google I/O 2019.
He confirmed it's intentionally not possible to force recreation on ViewModel. The right solution is to observe changes and act on them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With