5

I using MVVM on my Android application, on ViewModel I have many observers (from data binding) like ObservableBoolean, ObservableField, I read that I can use LiveData/MutableLiveData instead this observers... What's the difference? I can replace all my data binding observers by LiveData/MutableLiveData?

eg:

replace:

val loading: ObservableBoolean = ObservableBoolean()

By:

val loading: MutableLiveData<Boolean> = MutableLiveData()
aminography
  • 21,986
  • 13
  • 70
  • 74
felipe.rce
  • 237
  • 2
  • 8
  • 35

3 Answers3

6

Many times has passed and I learned a lot... Replace all Data Binding Observable by LiveData, because LiveData respect the Activity lifecycle and can be used in JetPack lib's, like Room, Coroutine...

felipe.rce
  • 237
  • 2
  • 8
  • 35
0

Depends on where you are reading the data from .

In our current project ,we read directly from RoomDB . RoomDB has the capability to send back a liveData object .

  1. Through your ViewModel , you do a query to RoomDB which returns a LiveData (RoomDB will be your Single Source of Truth)
    1. Your View say an Activity or Fragment - Subscribes to this viewmodel as an observer
    2. And you update the view as per the response returned .
    3. You could also directly bind the xml through Android Databinding(Using LiveData with Data Binding)

Mutable Data is used normally if you have any modifications after retrieving

This is a good Place to Start https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0

1nullpointer
  • 1,212
  • 1
  • 13
  • 19
  • 6
    I know what is LiveData, I asked what is the difference betwen LiveData and the Data Binding observables, and if is good to replace all them by LiveData – felipe.rce Oct 16 '18 at 07:30
0

If your aim is to just change basic properties of views in xml based on a change with the data in primitive data type in view model, it is simple and easy to use Data binding. For rest of the cases, live data is the only way.