-
Notifications
You must be signed in to change notification settings - Fork 0
Declaring live data observable in view model
Devrath edited this page Jul 11, 2021
·
2 revisions
- When we are creating an observable source like
live data
orflow
we need to give the ability to modify the live data by the components inside the ViewModel. Then expose a variable for outside so it can be observed. - Thus mutable state is for the view model since only the view model should modify it, thus it's private.
- We just expose the Live data since it just can be observed and not be modified and has no mutable state, thus it's public.
Declare in viewmodel
private val _images = MutableLiveData<Event<Resource<ImageResponse>>>()
val images: LiveData<Event<Resource<ImageResponse>>> = _images
Set the data in viewmodel
images.value = // set the state
Observe the live data from outside the view model, like activity or fragment
viewModel.images.observe(viewLifecycleOwner, Observer {})