Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewModel - how to force recreation on certain configuration changes

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)
    }
}
like image 298
AndrazP Avatar asked Nov 26 '18 08:11

AndrazP


People also ask

Does ViewModel survive configuration changes?

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.

What is the lifetime of ViewModel?

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.

Is ViewModel Life Cycle Aware?

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.

How does a ViewModel retain itself?

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.


1 Answers

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.

like image 63
AndrazP Avatar answered Sep 27 '22 18:09

AndrazP