Reputation: 55
What is the proper way to keep the actual app state in MVVM? A simple example to describe what I mean: I have two fragments and one global variable or object of my Class. I can change this variable or object on both fragments. Where should I keep this in code?
Upvotes: 1
Views: 1222
Reputation: 1023
The most easiest way is to use KTX extension function activityViewModels<VM : ViewModel>
see here.
From the doc:
Returns a property delegate to access parent activity's ViewModel ...
It will retrieve the ViewModel
instance provided by the ViewModelProviders
of the activity the fragments are attached to.
So any change on the view model instance will be reflected on all fragments.
Here a simple example:
class MVModel: ViewModel() {
var count = MutableLiveData(0)
fun increment() {
count.value = count.value!!.plus(1)
}
}
class MFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentMBinding.inflate(inflater, container, false)
val viewModel by activityViewModels<MVModel>()
binding.lifecycleOwner = this // <-- this enables MutableLiveData update the UI
binding.vm = viewModel
return binding.root
}
}
Upvotes: 2
Reputation:
You can make shared view model where all your components will access easily
Upvotes: 0