Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling a ViewModel instance reset the LiveData?

In Kotlin I'm using

viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)

To retrieve a ViewModel from the providers.

Inside my ViewModel I have something like this.

val liveChuchuData = MutableLiveData<DataChuchu>()

From my understanding this creates a final new variable of MutableLiveData right?

I remember when declaring MutableLiveDatas in ViewModel in Java, we create a function and then check if the MutableLiveData is null to only create it once. So what if I have a fragment that will also use the same ViewModel instance.

val liveChuchuData = MutableLiveData<DataChuchu>()

Will that line cause the current data to be reset, once called in a fragment?

like image 872
Hiroga Katageri Avatar asked Aug 09 '18 07:08

Hiroga Katageri


People also ask

What is the difference between LiveData and ViewModel?

ViewModel : Provides data to the UI and acts as a communication center between the Repository and the UI. Hides the backend from the UI. ViewModel instances survive device configuration changes. LiveData : A data holder class that follows the observer pattern, which means that it can be observed.

How does ViewModel retain data?

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. Architecture Components provides ViewModel helper class for the UI controller that is responsible for preparing data for the UI.

Does ViewModel hold data?

The ViewModel stores the app related data that isn't destroyed when activity or fragment is destroyed and recreated by the Android framework.

Why should you initialize and store LiveData in your ViewModel instead of a UI controller?

Why should you initialize and store LiveData in your ViewModel instead of a UI Controller? Both the ViewModel and LiveData are lifecycle aware. To ensure that the LiveData isn't destroyed when the UI Controller is destroyed. To hide or separate implementation details making your app more flexible.


Video Answer


1 Answers

Depends on what is the parent of your ViewModel. If parent is Acivity and in your Fragment you initialize your ViewModel with getActivity() instead of passing this, then you will reuse that ViewModel, but for example if you have two separate Fragments that initialize same ViewModel by passing this to ViewModelProvider then your ViewModel will have two separate instances and different data in them.

To have same data in ViewModel in two Fragments, you need to pass getActivity(); to ViewModelProvider when creating your ViewModel instance.


That said, YES, it will cause your data to be reset if you use this when creating ViewModel.


Hope this helps. Good luck :)

like image 155
Tomas Jablonskis Avatar answered Sep 24 '22 03:09

Tomas Jablonskis