Open In App

LiveData vs ObservableField in Android

Last Updated : 04 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

LiveData helps to reduce memory leaks and manual lifecycle handling. It also ensures that UI is always up to date with the data even when the app’s activity is restarted while we are still using our app. It is a part of the architecture patterns of android. It is used for observing changes in the view and updating the view when it is ACTIVE. Thus, LiveData is lifecycle aware.

An observable class that holds a parcelable object (allows objects to read and write from Parcels which can contain flattened data inside message containers). An object wrapper to make it observable. ObservableField classes may be used instead of creating an Observable object. If your object class has fewer properties to be updated or if you don’t want to observe every field in the object, you can use ObservableFields to update the UI. You can declare the variable as ObservableField and when the new data is set, the UI will be updated.

Unlike objects that implement Observable—such as observable fields—LiveData objects know about the lifecycle of the observers subscribed to the data changes. This knowledge enables many benefits, which are explained in The advantages of using LiveData. In Android Studio version 3.1 and higher, you can replace observable fields with LiveData objects in your data binding code. There are situations where you might prefer to use a View Model component that implements the Observable interface over using LiveData objects, even if you lose the lifecycle management capabilities of LiveData. Using a View Model component that implements Observable gives you more control over the binding adapters in your app. For example, this pattern gives you more control over the notifications when data changes, it also allows you to specify a custom method to set the value of an attribute in two-way data binding.

Similarities

  • Both work well with data binding which allows you to bind UI components in your XML layouts to data sources in your app.
  • Bound views automatically unsubscribe when in the background.
  • Plain Old Java Object classes can also use these changes.

Differences

  • LiveData allows for Plain Old Java Object subscribers to be lifecycle aware which means that if you have a property B that you want to update when A changes, you can opt to not receive updates when the attached view is inactive. This saves space/recourses in your app.
  • Background thread updates of ObservableField  are fast.  MutableLiveData.postData relatively slow.
  • Values of LiveData<T> and ObservableField<T> are always null, but the primitive implementations(something that doesn’t directly refer to algorithm or behavior) Observable -Integer, -Floating, -Boolean, etc are not null.
  • MutableLiveData<T> doesn’t take a constructor value to set on initialization.

When to Use What?

  • Do you have external events that may trigger data processing API, integration API, process planner, and process scheduler change in the View Model when the app is in the background? You should probably go for LiveData
  • Do you require value update on background threads to be fast and immediate? Use Observables
  • None of the above requirements?  You can use both but ObservableField is easy to use and you can change implementations based on your choice that you can’t do in live data.

Now, let’s understand ObservableField and why LiveData was required even when ObservableField was present.

  • ObservableField is not Lifecycle aware but LiveData is lifecycle aware and hence will notify only the observables which are “active”.
  • We have to do manual handling of Lifecycle awareness in ObservableField.

ViewModel + LiveData + Data Binding = Reactive UI

Kotlin




// LiveData
  
class SampleViewModel : ViewModel() {
  
    // Create a LiveData with a String
    val currentName : MutableLiveData<String> by lazy
    {
        MutableLiveData<String>()
    }
  
    // Rest of the ViewModel...
}
  
// Declaring it
val liveDataA = MutableLiveData<String>()
                // Trigger the value change
                liveDataA.value
    = someValue
    // Optionally, one could use liveDataA.postValue(value)
    // to get it set on the UI thread


What are the Benefits of Using LiveData?

  • No memory Leaks: As the observers are bound to the lifecycle of the app, when not required then it is destroyed.
  • No Crashes due to Stopped Activity: As the Activity is not in use, so is the LiveData. So the data streaming stops which stops the crashes in the back stack.
  • Configuration Changes: It handles the latest data when the view is recreated due to screen rotation.

You can use LiveData all the time, as long as there is a Lifecycle Owner to observe. I prefer to keep bound fields that are only relevant to the ViewModel as Observable and use LiveData for fields whose state changes are also relevant to the Activity or Fragment.

Java




// ObservableField
  
public class MyDataObject {
    private Context context;
    public final ObservableField<String> A
        = new ObservableField<String>();
    public final ObservableField<String> B
        = new ObservableField<String>();
    public final ObservableField<String> display
        = new ObservableField<String>(A, B) {
              @Override public String get()
              {
                  return context.getResources().getString(
                      R.string.name, first.get, last.get());
              }
          };
    public final ObservableInt age = new ObservableInt();
}




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads