ViewModel

MVVM 框架绕不开ViewModel。
Model, View在Android中都有很明确的对应,而ViewModel是一种基于Android架构组件形成的特定模式。

LiveData

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

LiveData是一个observable数据保持器类。与常规的observable数据不同,LiveData具有生命周期意识,这意味着它尊重其他应用组件的生命周期,例如activities, fragments, or services。此意识确保LiveData仅更新处于活动生命周期状态的 app component observers。

LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.

LiveData认为,如果observer的生命周期处于STARTED或RESUMED状态,则由Observer类表示的observer将处于活动状态。LiveData只向活动的observers通知更新。已被注册的用于监视LiveData对象的非活动observers不会收到有关更改的通知。

You can register an observer paired with an object that implements the LifecycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED. This is especially useful for activities and fragments because they can safely observe LiveData objects and not worry about leaks—activities and fragments are instantly unsubscribed when their lifecycles are destroyed.

您可以注册一个与实现LifecycleOwner接口的对象配对的观察者。当相应Lifecycle对象的状态更改为DESTORYED时,此关系允许移除观察者。这对于活动和片段特别有用,因为它们可以安全地观察LiveData对象,而不必担心泄漏。当活动和片段的生命周期destroyed,它们会立即unsubscribed。

使用LiveData有以下优点:

  • Ensures your UI matches your data state

LiveData follows the observer pattern. LiveData notifies Observer objects when underlying data(基础数据) changes. You can consolidate(巩固) your code to update the UI in these Observer objects. That way, you don't need to update the UI every time the app data changes because the observer does it for you.

  • No memory leaks

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

  • No crashes due to stopped activities

If the observer's lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

  • No more manual lifecycle handling

UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.

  • Always up to date data(始终更新数据)

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

  • Proper configuration changes

If an activity or fragment is recreated due to a configuration change, like device rotation(设备旋转), it immediately receives the latest available data.

  • Sharing resources(共享资源)

You can extend a LiveData object using the singleton(单例) pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extend LiveData.

LiveData 实例

简单的说,即"activity or fragment" observe() ViewModel.

Follow these steps to work with LiveData objects:

  • Create an instance of LiveData to hold a certain type of data. This is usually done within your ViewModel class.

  • Create an Observer object that defines the onChanged() method, which controls what happens when the LiveData object's held data changes. You usually create an Observer object in a UI controller, such as an activity or fragment.

  • Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

Note: You can register an observer without an associated LifecycleOwner object using the observeForever(Observer) method. In this case, the observer is considered to be always active and is therefore always notified about modifications. You can remove these observers calling the removeObserver(Observer) method. observeForever(Observer)用于注册一个没有关联LifecycleOwner对象的观察者,这里的observer永久激活。

When you update the value stored in the LiveData object, it triggers all registered observers as long as the attached LifecycleOwner is in the active state.
LiveData allows UI controller observers to subscribe to updates. When the data held by the LiveData object changes, the UI automatically updates in response.

更新LiveData对象中存储的值时,只要连接的LifecycleOwner处于活动状态,它就会触发所有已注册的观察者。LiveData允许UI controller observers to subscribe 更新。当LiveData对象所保存的数据发生更改时,UI会自动更新。

创建ViewModel

LiveData is a wrapper that can be used with any data, including objects that implement Collections, such as List. A LiveData object is usually stored within a ViewModel object and is accessed via a getter method, as demonstrated in the following example:

public class NameViewModel extends ViewModel {

// Create a LiveData with a String
// 这里只能使用可变的MutableLiveData,其继承于LiveData
private MutableLiveData<String> currentName;
    // 这里可以替代为LiveData,不可变
    public MutableLiveData<String> getCurrentName() {
        if (currentName == null) {
            currentName = new MutableLiveData<String>();
        }
        return currentName;
    }

// Rest of the ViewModel...
}

Note: Make sure to store LiveData objects that update the UI in ViewModel objects, as opposed to an activity or fragment, for the following reasons:
To avoid bloated activities and fragments. Now these UI controllers are responsible for displaying data but not holding data state.
To decouple LiveData instances from specific activity or fragment instances and allow LiveData objects to survive configuration changes.

注意:请确保在ViewModel对象中存储更新UI的LiveData对象,而不是活动或片段,原因如下:
避免臃肿的活动和碎片。现在,这些UI控制器负责显示数据,但不保存数据状态。
将LiveData实例与特定活动或片段实例解耦(decouple),并允许LiveData对象在配置更改后继续存在。

posted @ 2021-05-06 20:02  千心  阅读(378)  评论(0编辑  收藏  举报