Android Jetpack---LiveData is simple to use

LiveData is an observable data storage class. Unlike regular observable classes, LiveData is lifecycle aware, meaning it follows the lifecycle of other application components such as Activities, Fragments, or Services. This awareness ensures that LiveData only updates app component observers that are in an active lifecycle state. —Official explanation

https://developer.android.google.cn/topic/libraries/architecture/livedata?hl=zh_cn#kotlin

Some features of LiveData are as follows:

LiveData stores data; LiveData is a wrapper that can store any type of data.
LiveData is observable, which means that observers are notified when the data stored by the LiveData object changes.
LiveData is lifecycle aware. When you attach an observer to LiveData, the observer is associated with the LifecycleOwner (usually activity or fragment). LiveData only updates observers that are in an active lifecycle state such as STARTED or RESUMED. You can read more about LiveData and Observations here.

Advantage

  • Make sure the interface conforms to the data state
    LiveData follows the Observer pattern. LiveData notifies Observer objects when the underlying data changes. You can integrate code to update the interface in these Observer objects. This way, you don't need to update your UI every time your app's data changes, because the observer will do it for you.
  • No memory leaks
    Observers are bound to Lifecycle objects and clean up after their associated lifecycles are destroyed.
  • No crash due to Activity stopping
    If the observer's lifecycle is inactive (such as an Activity in the back stack), it will not receive any LiveData events.
  • No more manual lifecycle handling
    UI components just observe related data and don't stop or resume observing. LiveData will automatically manage all of these operations as it is aware of relevant lifecycle state changes as it observes.
  • Data is always up to date
    If a lifecycle becomes inactive, it will receive the latest data when it becomes active again. For example, an Activity that was once in the background receives the latest data as soon as it returns to the foreground.
  • Appropriate configuration changes
    If an Activity or Fragment is recreated due to a configuration change, such as a device rotation, it immediately receives the latest available data.
  • Shared resources
    You can extend the LiveData object using the singleton pattern to encapsulate system services so that they can be shared across applications. A LiveData object connects to the system service once, and then any observer that needs the corresponding resource simply observes the LiveData object.

Steps for usage

  • Create and store a certain type of LiveData
  • Create an Observer object that observes data changes
  • Use LiveData's observe() method to attach the Observer object
  • Update the LiveData object, the Observer listens to it, and updates the UI

Through the above steps, the update of the data is realized.

Create and store a certain type of LiveData

Through the popular MVVM architecture, we know that the creation of LiveData is generally done in ViewModel.

class NameViewModel : ViewModel() {

    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
}

Create an Observer object that observes data changes

class NameActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 创建Observer对象,监听LiveData数据变化,通过他来更新UI
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            nameTextView.text = newName
        }
        
}

Use LiveData's observe() method to attach the Observer object

class NameActivity : AppCompatActivity() {

    private val model: NameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        // 创建Observer对象,监听LiveData数据变化,通过他来更新UI
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            nameTextView.text = newName
        }

        // 把Observer对象附加在LiveData,以观察到数据变化
        model.currentName.observe(this, nameObserver)
    }
}

Update LiveData

We change the data inside LiveData by clicking the button.
In this way, the Observer will update the UI when it listens.

button.setOnClickListener {
    val anotherName = "John Doe"
    model.currentName.setValue(anotherName)
}

Calling setValue(T) in this example causes the observer to call its onChanged() method with the value John Doe. This example demonstrates a button press, but you could call setValue() or postValue() to update mName for a variety of reasons, including in response to a network request or when a database load completes. In all cases, calling setValue() or postValue() will trigger the observer and update the interface.

Note: You must call the setValue(T) method to update the LiveData object from the main thread. If you execute your code in a worker thread, you can instead use the postValue(T) method to update the LiveData object.

Note: The problem of data backfilling.

Guess you like

Origin blog.csdn.net/ecliujianbo/article/details/125314753