'Advantage of LiveData Over Observer Object In Terms of Avoiding Memory Leak

I am trying to understand if there is any advantage of LiveData over Observable objects in terms of avoiding memory leak when performing data binding. So far, I understand that LiveData is a lifecycle aware observable class, however according to Android Data Binding Library — from Observable Fields to LiveData in two steps :

LiveData is lifecycle-aware but this is not a huge advantage with respect to Observable Fields because Data Binding already checks when the view is active.

I want to clarify this since LiveData's lifecycle aware feature is touted as the go to class for avoiding memory leaks:

No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.



Solution 1:[1]

As mentioned in my comment and article/documentation, LiveData is just a better version of Observable. There's no reason to not use LiveData unless you're absolutely sure you don't need the extra value added.

The LiveData Overview explains how they avoid memory leaks by the system automatically cleaning them up when their associated Lifecycle (Fragment/Activity) object is destroyed. From the documentation of LiveData:

An observer added with a Lifecycle will be automatically removed if the corresponding Lifecycle moves to DESTROYED state. This is especially useful for activities and fragments where they can safely observe LiveData and not worry about leaks: they will be instantly unsubscribed when they are destroyed.

If you look at Lifecycle.State you'll see the list of states, which correspond to various 'on' callbacks in your Activity/Fragment (e.g. CREATED -> onCreate)

Resource leaks can be defined as failure to release unused objects from the system. One common type of memory leak in Android is keeping a reference to a Context alive when its Activity/Fragment (UI) is out of scope. If a Context is used in a background task, Singleton object, static variable, or some other source, and the associated UI object goes out of scope, the garbage collector will be unable to free its memory since there is still at least one reference to the Context, resulting in a memory leak. For example, lets say you create a class that does some background task (e.g. database access), but it requires a Context. If your UI object is destroyed before that task is complete and the Context is not dereferenced, that will result in a memory leak.

So, to summarize, LiveData/Observable objects handle the boilerplate code of destroying or unreferencing themselves from associated Activity/Fragment when they are no longer needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zen_of_kermit