LiveData Overview
LiveData is an observable data memory class: Unlike conventional observable classes, LiveData has life cycle awareness, meaning it follows the life cycle of other application components (such as Activity, Fragment, or Service); this perception ensures that LiveData only updates the observers of application component in active life cycle states.
If the observer (represented by the Observer class) has a STARTED or RESUMED state, LiveData considers that observer active; LiveData only notifies the active observer of updates, and inactive observers registered to observe LiveData objects will not receive a change notification
You can register observers paired with objects that implement the LifecycleOwner interface; with this relationship, the observer can be removed when the state of the corresponding Lifecycle object becomes DESTROYED; this is especially useful for Activity and Fragment because they can observe LiveData objects with confidence without worrying about leakage (the system will unsubscribe immediately when the lifecycles of Activity and Fragment are destroyed)
Advantages of LiveData
LiveData follows observer mode; LiveData notifies the Observer object when the lifecycle state changes. You can integrate code to update the interface in these Observer objects. The observer can update the interface every time the change occurs, rather than every time the application data changes.
No memory leaks occur
Observers will bind to Lifecycle objects and clean up themselves after their associated lifecycle is destroyed. They will not crash due to the stop of the Activity
If the observer's lifecycle is inactive (such as the activity in the stack), it will not receive any LiveData events
No more manual life cycle processing
The interface component only observes the relevant data and will not stop or resume observation. LiveData will automatically manage all these operations because it can perceive relevant lifecycle state changes when viewed
Data is always up to date
If the life cycle becomes inactive, it receives the latest data when it becomes active again. For example, an Activity that was once in the background will receive the latest data immediately after returning to the foreground
Appropriate configuration changes
If the Activity or Fragment is recreated due to a configuration change (such as device rotation), it will immediately receive the latest available data
Share resources
You can extend LiveData objects using singleton pattern to encapsulate system services so that they can be shared in your application; LiveData objects are connected to the system services once, and then any observer who needs the corresponding resource only needs to observe the LiveData object
LiveData usage
First, we need to introduce the LiveData library. Because dependencies have a transmission function, we can rely on the following one.
implementation ":lifecycle-extensions:2.2.0"
LiveData should generally be used in combination with ViewModel. ViewModel will be introduced separately later. For the sake of demonstration convenience, we will use LiveData directly in Activity.
1 Basic use of LiveData
class TestActivity : AppCompatActivity() { private val TAG by lazy { TestActivity:: } private val data = MutableLiveData<String>() override fun onCreate(savedInstanceState: Bundle?) { (savedInstanceState) setContentView(.activity_main) (this, Observer { (TAG, "value: ${} + $it ") }) } fun onTest(view: View) { ("LiveData") } //Print information TestActivity: value: LiveData }
LiveData is an abstract class, and MutableLiveData is its implementation class; first declare a MutableLiveData object, and then call (lifecycleOwner, observer). The first parameter is lifecycleOwner. It is mentioned in detail in the Lifecycle Principles chapter. It is a class closely related to the lifecycle. Here, the LiveData component is bound to the lifecycle. The second parameter is a callback, which will be called when data is updated. Then when the button is clicked to execute the onTest method, the MutableLiveData value will be updated, resulting in the callback being called and simulated data update
2 ()
class TestActivity : AppCompatActivity() { private val data = MutableLiveData<String>() override fun onCreate(savedInstanceState: Bundle?) { (savedInstanceState) setContentView(.activity_main) (this, Observer { (TAG, "Changed1:$it") }) val transformedLiveData: LiveData<String> = (data) { "$it+map" } (this, Observer { (TAG, "Changed2:$it") }) } fun onTest(view: View) { ("LiveData") } }
//Print as follows
TestActivity:Changed1:LiveData
TestActivity:Changed2:LiveData+map
The above code uses(data)
WillLiveData
The stored value is changed and eventually printed by the observer callback
3 ()
class TestActivity : AppCompatActivity() { private lateinit var data1: MutableLiveData<String> private lateinit var data2: MutableLiveData<String> private lateinit var switchData: MutableLiveData<Boolean> override fun onCreate(savedInstanceState: Bundle?) { (savedInstanceState) setContentView(.activity_main) data1 = MutableLiveData() data2 = MutableLiveData() switchData = MutableLiveData() val transformedLiveData: LiveData<String> = (switchData) { if (it) { (TAG, "----------true---data1--") data1 } else { (TAG, "----------false---data2--") data2 } } (this, Observer { (TAG, "onChanged:$it") }) } fun onTest(view: View) { (true) ("data1") ("data2") } }
//Print information as follows
TestActivity: ----------true---data1--
TestActivity: onChanged:data1
() is very similar to (). It can switch listening freely as needed. The difference between () is that it needs to return a LiveData object inside its method.
4 () Merge data
class TestActivity : AppCompatActivity() { private val data1 = MutableLiveData<String>() private val data2 = MutableLiveData<String>() private val mediatorLiveData = MediatorLiveData<String>() override fun onCreate(savedInstanceState: Bundle?) { (savedInstanceState) setContentView(.activity_main) (data1) { (TAG, "onChanged1:$it") = it } (data2) { (TAG, "onChanged2:$it") = it } (this, Observer { (TAG, "onChanged:$it") }) } fun onTest(view: View) { ("data1") } }
//Print information as follows
TestActivity:onChanged1:data1
TestActivity:onChanged:data1
Two LiveData objects have been added, which can store multiple LiveData data sets internally to monitor changes in multiple data. For example, when the data1 data changes when the onTest is clicked, the change will be listened to. Similarly, if the data2 data source changes, it will also be listened to.
This is the article about the use of Jetpack component LiveData for Android development. For more information about Jetpack component LiveData, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!