How To Use Viewmodel Singleton For Activities?
Solution 1:
Another way is to have one singleton repository to hold your user data and each viewModel can have that repository and share the same data between activities.
Solution 2:
Based on this part of the documentation: https://developer.android.com/topic/libraries/architecture/livedata#extend_livedata
The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services. To keep the example simple, you can implement the LiveData class as a singleton as follows:
You can create a singleton for your view model like I did here:
companionobject{
privatelateinitvar instance: ViewModelProfile
@MainThreadfungetInstance(userId: String): ViewModelProfile{
instance = if(::instance.isInitialized) instance else ViewModelProfile(userId)
return instance
}
}
Then I call it and get instance anywhere like this:
val profileVModel = ViewModelProfile.getInstance(user.uid)
Solution 3:
If you want to share common ViewModel between ABC activities, then it is suggested to keep them as 3 fragments in a single Activity, create ViewModel of that Activity which can be shared among all three fragments A, B, and C.
Also what you are trying to achieve with activities is like this, suppose you have done some operation in activity A, if you want Activity B and C to get notified about them then they need to be running to get notified, which won't be happening, so instead you should use Intent or Bundle to pass needed information when the activity get started.
Updated
There are other ways as well to achieve similar kind of functionality like,
This will allow you to have application level access of state, which can be accessed by any Activity or Fragment
Post a Comment for "How To Use Viewmodel Singleton For Activities?"