Skip to content

Declaring live data observable in view model

Devrath edited this page Jul 11, 2021 · 2 revisions

Declaring live data observable in the view model

  • When we are creating an observable source like live data or flow 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 {})
Clone this wiki locally