BehaviorSubject vs LiveData

LiveData and BehaviorSubject both have reactive capabilities, namely

  • When that item changes notify all active subscribers and keep doing the same for future changes.

LiveData’s observers always receive events on the main thread, BehaviorSubject not necessarily do that but can be fixed by subject.observeOn(AndroidSchedulers.mainThread()).

What is the main difference?

Let’s take an example with BehaviorSubject:

  • When activity loads, view model does a network call and updates result to a BehaviorSubject.
  • Activity is observing the BehaviorSubject, so even after rotation config change it will receive the latest item and future items.
  • In Activity, as soon as BehaviorSubject emits, I need to do a Fragment Transaction to show the data received from network.

Now do you see any issues here? It might not be apparent. Now after running the app, as soon as the network call starts, press home button and observe the app crashes after network call completes. Why? Because you can’t do a fragment transaction when the activity is in background i.e after onSavedInstanceState() was called. Doing so will cause IllegalStateException.

Now replace BehaviorSubject with LiveData and observe the app works like expected. How?

LiveData emits the item only when Activity/Fragment is in active state, meaning visible to the user, until then cache the latest received item.

When you press home button, LiveData knows that because for every observe call you are passing a LifecycleOwner. So LiveData does not emit the item immediately, it waits until the Owner comes active (resumed) then emits the item. So FragmentTranstion will happen only after you resume the app which is safe and good. 

Add a Comment

Your email address will not be published.