美文网首页设计模式架构androidlivedata
[翻译]LiveData 概述( LiveData overvi

[翻译]LiveData 概述( LiveData overvi

作者: 三秋桂子仪同三司 | 来源:发表于2018-08-23 17:02 被阅读0次

    前言:

    这是一篇Android官方关于LiveData介绍的翻译,正如名字所展示的,它是对存活数据的一个封装类,把网络请求,数据库查询或者其他方式得到的数据保存在 LiveData 对象中,并且注册观察者监听 LiveData 内容的变化,当数据变化时,更新 UI 组件。是一个观察者设计模式的应用。结合生命周期感知组件,就能在 UI 组件处于活动状态时,才会收到 LiveData 数据变化的通知,文章中列举了这种模式的几点优势。简单来说,一是把数据和UI组件解耦,二是避免不必要的UI更新。
    我的翻译风格是一段一段地贴出原文,然后在下面给出翻译,主要是因为自己水平有限,翻译的不通顺的地方,可以查看原文是怎么说的。


    原文:

    LiveData overview

    译文:

    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 是生命周期感知(lifecycle-aware)的,意味着它遵守其他应用组件的生命周期,例如activities,fragments 或者 services。这种感知确保 LiveData 只会在生命周期在活动状态时更新应用组件观察者。

    原文:

    Note: To import LiveData components into your Android project, see Adding Components to your Project.

    译文:

    注意:要导入 LiveData 组件到你的Android工程,查看添加组件到你的项目.

    原文:

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

    译文:

    LiveData 认为一个用 Observer 类表示的观察者(observer),如果它的生命周期在 STARTED 或者 RESUMED 状态,则它在活动状态。LiveData 只会把相关更新通知给活动的观察者。已注册的非活动状态的观察者不会被通知变化。

    原文:

    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 接口的对象配对。这种关系使得当相应的生命周期对象的状态变成 DESTROYED 时,观察者被移出。这对 activities 和 fragments 非常有用,因为他们可以安全地观察 LiveData,并且不用担心泄漏,当它们的生命周期是已销毁(destroyed)时,activities 和 fragments 立即取消订阅。

    原文:

    For more information about how to use LiveData, see Work with LiveData objects.

    译文:

    更多关于如何使用 LiveData 的信息,查看“用 LiveData 对象工作”

    原文:

    The advantages of using LiveData

    Using LiveData provides the following advantages:

    译文:

    使用 LiveData 的好处

    使用 LiveData 提供了下面的好处:

    原文:

    Ensures your UI matches your data state

    LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there's a change.

    译文:

    确保你的 UI 和你的数据状态相匹配

    LiveData 遵循观察者模式,当生命周期状态变化时,LiveData 通知观察者(Observer)对象。你可以在这些观察者对象中整合你更新UI的代码,而不是应用数据每次发生变化时更新UI。每次有变化时你的观察者能够更新UI。

    原文:

    No memory leaks

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

    译文:

    没有内存泄漏

    观察者(Observers ) 被绑定到生命周期(Lifecycle)对象上,当它们所关联的生命周期是已销毁 (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.

    译文:

    没有 activities stopped 引起的崩溃

    如果观察者的生命周期是不活动,例如一个 activity 在回退栈中的情况下,它不会收到任何 LiveData 事件。

    原文:

    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.

    译文:

    没有更多手动的生命周期处理

    UI 组件仅仅观察相关的数据,并且不要停止或者恢复观察。LiveData 自动管理所有这些,因为在观察阶段它是知道相关生命周期状态变化的。

    原文:

    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.

    译文:

    经常更新到最新数据

    如果一个生命周期变成不活动,直到再次变成活动状态它才能收到最新数据。例如,一个在后台的 activity 刚好在回到前台后会接收最新的数据。

    原文:

    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.

    译文:

    合适的配置变化

    如果一个 activity 或者 fragment 因为配置变化而重新创建,例如设备旋转,它立刻能收到最新的可用数据。

    原文:

    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 对象,使用单例模式来包装系统服务,这样它们可以在你的APP中共享。LiveData 对象连接一次系统服务,然后任何需要资源的观察者可以只观察 LiveData 对象,更多信息参阅“扩展 LiveData”

    原文:

    Work with LiveData objects

    Follow these steps to work with LiveData objects:

    译文:

    用 LiveData 对象工作

    按照这些步骤用 LiveData 对象工作

    原文:

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

    译文:

    1. 创建一个 LiveData 实例来保存一个确定类型的数据,这通常用你的 ViewModel 类完成,

    原文:

    1. 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.

    译文:

    1. 创建一个 Observer 对象,它定义了 onChanged() 方法,当 LiveData 对象保存的数据变化时这个方法控制发生了什么。你通常在一个UI控制器里面创建一个 Observer 对象,例如一个 activity 或者 fragment。

    原文:

    1. 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.

    译文:

    1. 用 observe() 方法把 Observer 对象附加到 LiveData 对象上。observe() 方法接收一个 LifecycleOwner 对象,它给 Observer 对象订阅了 LiveData 对象,因此它会被通知变化。你通常在一个 UI 控制器里面附加 Observer 对象,例如一个 activity 或者 fragment。

    原文:

    Note: You can register an observer without an associated LifecycleOwner object using theobserveForever(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.

    译文:

    注意:你可以注册一个 observer,并不关联 LifecycleOwner 对象,使用 observeForever(Observer) 方法。在这种情形下,observer 被认为是一直活动的,因此总是会被通知变化。你可以调用 removeObserver(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 对象中的值时,它触发所有已注册的观察者,如果依附的 LifecycleOwner 在活动状态。

    原文:

    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 允许 UI 控制器观察者订阅更新,当用 LiveData 对象保存的数据发生变化时,作为回应,UI 自动更新。

    原文:

    Create LiveData objects

    LiveData is a wrapper that can be used with any data, including objects that implement [Collections](https://developer.android.com/reference/java/util/Collections.html), such as [List](https://developer.android.com/reference/java/util/List.html). A LiveData object is usually stored within a ViewModel object and is accessed via a getter method, as demonstrated in the following example:

    译文:

    创建 LiveData 对象

    LiveData 是一个包装器,可以和任何数据一起使用,包括实现容器(Collections)接口的对象,例如 List。一个 LiveData 对象通常保存在一个 ViewModel 对象中,并且通过一个 getter 方法访问,在下面的例子进行演示:

    public class NameViewModel extends ViewModel {
    
    // Create a LiveData with a String
    private MutableLiveData<String> mCurrentName;
    
        public MutableLiveData<String> getCurrentName() {
            if (mCurrentName == null) {
                mCurrentName = new MutableLiveData<String>();
            }
            return mCurrentName;
        }
    
    // Rest of the ViewModel...
    }
    

    原文:

    Initially, the data in a LiveData object is not set.

    译文:

    一开始,LiveData 对象中的数据没有设置。

    原文:

    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.

    译文:

    注意: 确保更新 UI 的 LiveData 对象存储在 ViewModel 对象里面,与之相对的是在一个 activity 或者 fragment中,因为以下原因:
    避免 activities 和 fragments 臃肿。现在这些 UI 控制器负责显示数据,但不保存数据状态。
    从特定的 activity 或者 fragment 实例中分离 LiveData 实例,并且使得 LiveData 对象在配置改变时存活。

    原文:

    You can read more about the benefits and usage of the ViewModel class in the ViewModel guide.

    译文:

    你可以在 [ViewModel 指导]中(https://developer.android.com/topic/libraries/architecture/viewmodel.html) 读到更多关于 ViewModel 类的好处和用法。

    原文:

    Observe LiveData objects

    In most cases, an app component’s [onCreate()](https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)) method is the right place to begin observing a LiveData object for the following reasons:

    译文:

    观察 LiveData 对象

    在大多数情况下,一个应用组件的 onCreate() 方法是开始观察一个 LiveData 对象的合适位置,因为下面的原因:

    原文:

    • To ensure the system doesn’t make redundant calls from an activity or fragment’s [onResume()](https://developer.android.com/reference/android/app/Activity.html#onResume()) method.

    译文:

    确保系统不会产生来自一个 activity 或者 fragment 的 onResume() 方法的冗余调用。

    原文:

    • To ensure that the activity or fragment has data that it can display as soon as it becomes active. As soon as an app component is in the STARTED state, it receives the most recent value from the LiveData objects it’s observing. This only occurs if the LiveData object to be observed has been set.

    译文:

    确保 activity 或者 fragment 在变成活动状态后能尽可能快地有可显示数据。一旦一个应用组件在 STARTED 状态,它从自己正在观察的 LiveData 对象收到最近的值,这只会在被观察的 LiveData 已经更新时才会发生。

    原文:

    Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.

    译文:

    通常,LiveData 只会在数据变化时分发更新,并且只会分发给活动的观察者。这个行为的一个例外是,观察者从不活动状态变成活动状态时也会收到一个更新。此外,如果观察者再一次从不活动变成活动,它只收到一个更新,如果自从它最后一次变成活动状态时,值已经发生了变化。

    原文:

    The following sample code illustrates how to start observing a LiveData object:

    译文:

    下面的示例代码说明如何开始观察一个 LiveData 对象。

    public class NameActivity extends AppCompatActivity {
    
        private NameViewModel mModel;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Other code to setup the activity...
    
            // Get the ViewModel.
            mModel = ViewModelProviders.of(this).get(NameViewModel.class);
    
    
            // Create the observer which updates the UI.
            final Observer<String> nameObserver = new Observer<String>() {
                @Override
                public void onChanged(@Nullable final String newName) {
                    // Update the UI, in this case, a TextView.
                    mNameTextView.setText(newName);
                }
            };
    
            // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
            mModel.getCurrentName().observe(this, nameObserver);
        }
    }
    

    原文:

    After observe() is called with nameObserver passed as parameter, onChanged() is immediately invoked providing the most recent value stored in mCurrentName. If the LiveData object hasn't set a value in mCurrentName, onChanged() is not called.

    译文:

    当 nameObserver 作为参数传递给 observe() 方法调用以后,onChanged() 立刻被调用并提供了最近存储在 mCurrentName 中的值,如果 LiveData 还没在 mCurrentName 中设置一个值,onChanged() 不会被调用。

    原文:

    Update LiveData objects

    LiveData has no publicly available methods to update the stored data. The MutableLiveData class exposes thesetValue(T) and postValue(T) methods publicly and you must use these if you need to edit the value stored in a LiveData object. Usually MutableLiveData is used in the ViewModel and then the ViewModel only exposes immutable LiveData objects to the observers.

    译文:

    更新 LiveData 对象

    LiveData 没有公开可用的方法来更新存储的数据,MutableLiveData 类公开地暴露了 setValue(T) 和 postValue(T) 方法,并且如果你需要编辑存储在一个 LiveData 对象中的值,你必须用这些方法。通常 MutableLiveData 被用在 ViewModel 中而且 ViewModel 只暴露不可变的 LiveData 给观察者。

    译注:

    关于不可变对象,可以参看 《Effective Java 第二版》的 “Item 15: Minimize mutability”,上面这段话的意思是:Observer 的 onChanged 方法中传递的参数是不可修改的,也就是说,在这个方法中修改参数的值,是不会影响 LiveData 中保存的值的。

    原文:

    After you have set up the observer relationship, you can then update the value of the LiveData object, as illustrated by the following example, which triggers all observers when the user taps a button:

    译文:

    当你建立起观察关联以后,你可以更新 LiveData 的值,像下面的示例展示的,当用户轻点一个按钮,它会触发所有观察者。

    mButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String anotherName = "John Doe";
            mModel.getCurrentName().setValue(anotherName);
        }
    });
    

    原文:

    Calling setValue(T) in the example results in the observers calling their onChanged() methods with the value John Doe. The example shows a button press, but setValue() or postValue() could be called to update mName for a variety of reasons, including in response to a network request or a database load completing; in all cases, the call to setValue() or postValue() triggers observers and updates the UI.

    译文:

    例子中调用 setValue(T) 导致观察者带着 John Doe 实参调用它们的 onChanged()方法。这个例子展示了一个按钮点击,但是在多种多样的情景下可以调用 setValue() 或者 postValue() 更新 mName ,包括网络请求的响应,数据库加载完成。一概而论,setValue() 或者 postValue() 调用会触发观察者并且更新UI。

    原文:

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

    译文:

    注意:你必须在主线程调用 setValue(T) 方法来更新 LiveData 对象。如果代码运行在一个工作线程,你可以使用 postValue(T) 方法来更新 LiveData 对象。

    原文:

    Use LiveData with Room

    The Room persistence library supports observable queries, which return LiveData objects. Observable queries are written as part of a Database Access Object (DAO).

    译文:

    和 Room 一起使用 LiveData

    Room 持久化库支持可观察查询,它返回 LiveData 对象,可观察查询是数据库访问对象(DAO)的一部分。

    原文:

    Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database. You can read more about Room and DAOs in the Room persistent library guide.

    译文:

    Room 生成所有更新 LiveData 对象所需要的代码,生成的代码需要时在一个后台线程运行异步查询。这种模式对于显示在UI上的数据和存储在数据库中的数据保持同步很是有用。你可以在 Room 持久化库指导 阅读更多关于 Room 和 DAOs。

    原文:

    Extend LiveData

    LiveData considers an observer to be in an active state if the observer's lifecycle is in either the STARTED or RESUMEDstates The following sample code illustrates how to extend the LiveData class:

    原文:

    扩展 LiveData

    如果观察者的生命周期是 STARTED 状态或者 RESUMED 状态, LiveData 认为一个观察者在活动状态,下面的示例代码说明如何扩展 LiveData 类:

    public class StockLiveData extends LiveData<BigDecimal> {
        private StockManager mStockManager;
    
        private SimplePriceListener mListener = new SimplePriceListener() {
            @Override
            public void onPriceChanged(BigDecimal price) {
                setValue(price);
            }
        };
    
        public StockLiveData(String symbol) {
            mStockManager = new StockManager(symbol);
        }
    
        @Override
        protected void onActive() {
            mStockManager.requestPriceUpdates(mListener);
        }
    
        @Override
        protected void onInactive() {
            mStockManager.removeUpdates(mListener);
        }
    }
    

    原文:

    The implementation of the price listener in this example includes the following important methods:

    • The onActive() method is called when the LiveData object has an active observer. This means you need to start observing the stock price updates from this method.
    • The onInactive() method is called when the LiveData object doesn't have any active observers. Since no observers are listening, there is no reason to stay connected to the StockManager service.
    • The setValue(T) method updates the value of the LiveData instance and notifies any active observers about the change.

    译文:

    这个例子中的 price listener 实现包括下面重要的方法:

    • 当 LiveData 对象有一个活动的观察者时,onActive() 方法被调用,这意味着你需要从这个方法开始观察股票价格变化。
    • 当 LiveData 对象不再有任何活动的观察者时,onInactive()` 方法被调用,既然没有观察者在监听,也就没有和 StockManager 服务保持连接的理由。
    • setValue(T) 方法更新 LiveData 实例的值,并且把更新通知每一个活动的观察者。

    原文:

    You can use the StockLiveData class as follows:

    译文:

    你可以像下面这样使用 StockLiveData 类

    public class MyFragment extends Fragment {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            LiveData<BigDecimal> myPriceListener = ...;
            myPriceListener.observe(this, price -> {
                // Update the UI.
            });
        }
    }
    

    原文:

    The observe() method passes the fragment, which is an instance of LifecycleOwner, as the first argument. Doing so denotes that this observer is bound to the Lifecycle object associated with the owner, meaning:

    • If the Lifecycle object is not in an active state, then the observer isn't called even if the value changes.
    • After the Lifecycle object is destroyed, the observer is automatically removed.

    译文:

    observe() 方法传递 fragment, 它是一个 LifecycleOwner 实例,作为第一个参数。这样做表示这个观察者被绑定到了和所有者关联的 Lifecycle 对象,意味着:

    • 如果 Lifecycle 对象不在活动状态,那么即使值发生了变化,观察者不会被调用。
    • Lifecycle 对象销毁以后,观察者被自动移除。

    原文:

    The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services. To keep the example simple, you can implement the LiveData class as a singleton as follows:

    译文:

    事实是 LiveData 对象是生命周期感知的,意味着你可以在多个 activities,fragments 和 services 中共享它们。为了保持示例简单,你可以像下面一样,用一个单例模式实现 LiveData 类:

    public class StockLiveData extends LiveData<BigDecimal> {
        private static StockLiveData sInstance;
        private StockManager mStockManager;
    
        private SimplePriceListener mListener = new SimplePriceListener() {
            @Override
            public void onPriceChanged(BigDecimal price) {
                setValue(price);
            }
        };
    
        @MainThread
        public static StockLiveData get(String symbol) {
            if (sInstance == null) {
                sInstance = new StockLiveData(symbol);
            }
            return sInstance;
        }
    
        private StockLiveData(String symbol) {
            mStockManager = new StockManager(symbol);
        }
    
        @Override
        protected void onActive() {
            mStockManager.requestPriceUpdates(mListener);
        }
    
        @Override
        protected void onInactive() {
            mStockManager.removeUpdates(mListener);
        }
    }
    

    原文:

    And you can use it in the fragment as follows:

    译文:

    你可以这样在 fragment 中实用它,如下:

    public class MyFragment extends Fragment {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            StockLiveData.get(getActivity()).observe(this, price -> {
                // Update the UI.
            });
        }
    }
    

    原文:

    Multiple fragments and activities can observe the MyPriceListener instance. LiveData only connects to the system service if one or more of them is visible and active.

    译文:

    多个 fragments 和 activities 可以观察 MyPriceListener 实例,LiveData 只在其中一个或者多个处于可见或者活动时连接到系统服务。

    原文:

    Transform LiveData

    You may want to make changes to the value stored in a LiveData object before dispatching it to the observers, or you may need to return a different LiveData instance based on the value of another one. The Lifecycle package provides the Transformations class which includes helper methods that support these scenarios.

    译文:

    改造 LiveData

    你可能想要在分发给观察者之前,修改存储在一个 LiveData 对象中的值,或者你需要基于另一个值返回一个不同的 LiveData 实例。Lifecycle 包提供了 Transformations 类,它提供了支持这种场景的辅助方法。

    原文:

    Transformations.map()

    Applies a function on the value stored in the LiveData object, and propagates the result downstream.

    译文:

    Transformations.map()

    在存储在 LiveData 对象中的值应用一个函数,并且向下传递结果。

    LiveData<User> userLiveData = ...;
    LiveData<String> userName = Transformations.map(userLiveData, user -> {
        user.name + " " + user.lastName
    });
    

    原文:

    Transformations.switchMap()

    Similar to map(), applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object, as illustrated by the following example:

    译文:

    Transformations.switchMap()

    和 map() 相似,在存储在 LiveData对象中的值应用一个函数,解开并且向下分发结果,传递给 switchMap() 的函数必须返回一个 LiveData 对象,想下面的例子展示的一样:

    private LiveData<User> getUser(String id) {
      ...;
    }
    
    LiveData<String> userId = ...;
    LiveData<User> user = Transformations.switchMap(userId, id -> getUser(id) );
    

    原文:

    You can use transformation methods to carry information across the observer's lifecycle. The transformations aren't calculated unless an observer is watching the returned LiveData object. Because the transformations are calculated lazily, lifecycle-related behavior is implicitly passed down without requiring additional explicit calls or dependencies.

    译文:

    你可以使用转换方法携带信息贯穿观察者的生命周期。转换不会计算,除非有一个观察者在监视返回的 LiveData 对象。因为转换是延迟计算的,生命周期相关的行为是隐式传递下来的,不需要额外的显式调用或者依赖。

    原文:

    If you think you need a Lifecycle object inside a ViewModel object, a transformation is probably a better solution. For example, assume that you have a UI component that accepts an address and returns the postal code for that address. You can implement the naive ViewModel for this component as illustrated by the following sample code:

    译文:

    如果你觉得在 ViewModel 对象中需要一个生命周期对象,一个转换或许是更好的解决方案,例如,假设你有一个 UI 组件接收一个地址,返回这个地址的邮政编码,你可以给这个组件实现一个简单的 ViewModel,像下面的示例代码展示的一样:

    class MyViewModel extends ViewModel {
        private final PostalCodeRepository repository;
        public MyViewModel(PostalCodeRepository repository) {
           this.repository = repository;
        }
    
        private LiveData<String> getPostalCode(String address) {
           // DON'T DO THIS
           return repository.getPostCode(address);
        }
    }
    

    原文:

    The UI component then needs to unregister from the previous LiveData object and register to the new instance each time it calls getPostalCode(). In addition, if the UI component is recreated, it triggers another call to the repository.getPostCode() method instead of using the previous call’s result.

    译文:

    UI 组件每次调用 getPostalCode() 需要从之前的 LiveData 对象反注册,然后注册到新的实例。此外,如果 UI 组件被重新创建,它触发另一个 repository.getPostCode() 方法调用,而不是使用之前的调用结果。

    原文:

    Instead, you can implement the postal code lookup as a transformation of the address input, as shown in the following example:

    译文:

    替代做法是,你可以按照一个输入地址转换来实现邮政编码查找,像下面的示例显示的一样:

    class MyViewModel extends ViewModel {
        private final PostalCodeRepository repository;
        private final MutableLiveData<String> addressInput = new MutableLiveData();
        public final LiveData<String> postalCode =
                Transformations.switchMap(addressInput, (address) -> {
                    return repository.getPostCode(address);
                 });
    
      public MyViewModel(PostalCodeRepository repository) {
          this.repository = repository
      }
    
      private void setInput(String address) {
          addressInput.setValue(address);
      }
    }
    

    原文:

    In this case, the postalCode field is public and final, because the field never changes. The postalCode field is defined as a transformation of the addressInput, which means that the repository.getPostCode() method is called when addressInput changes. This is true if there is an active observer, if there are no active observers at the time repository.getPostCode() is called, no calculations are made until an observer is added.

    译文:

    在这种情况下,postalCode 成员变量是公开的(public )而且不可变的(final),因为这个成员变量从不会改变。postalCode 成员变量是作为 addressInput 的转换定义的,这意味着 repository.getPostCode() 方法在 addressInput 改变时被调用,当有一个活动的观察者时时这样的,如果 repository.getPostCode() 被调用的时刻还没有活动的观察者,没有计算执行,直到一个观察者被添加进来。

    原文:

    This mechanism allows lower levels of the app to create LiveData objects that are lazily calculated on demand. A ViewModel object can easily obtain references to LiveData objects and then define transformation rules on top of them.

    译文:

    这个机制允许应用下层创建 LiveData 对象,它根据需要延迟计算,一个 ViewModel 对象可以容易获取 LiveData 对象的引用,然后在顶层定义它们的转换规则。

    原文:

    Create new transformations

    There are a dozen different specific transformation that may be useful in your app, but they aren’t provided by default. To implement your own transformation you can you use the MediatorLiveData class, which listens to otherLiveData objects and processes events emitted by them. MediatorLiveData correctly propagates its state to the source LiveData object. To learn more about this pattern, see the reference documentation of the Transformationsclass.

    译文:

    创建新的转换

    在你的应用中有很多不同的特定转换可能会很有用,但是默认是没有提供的。要实现你自己的转换,你可以使用 MediatorLiveData 类,它监听其他 LiveData 对象并且处理它们发出的事件。MediatorLiveData 正确地传递它的状态到源 LiveData 对象。了解更多关于这种模式,查看 Transformations 类的参考文档。

    原文:

    Merge multiple LiveData sources

    MediatorLiveData is a subclass of LiveData that allows you to merge multiple LiveData sources. Observers of MediatorLiveData objects are then triggered whenever any of the original LiveData source objects change.

    译文:

    合并多个 LiveData 源

    MediatorLiveData 是 LiveData 的子类,它允许你合并多个 LiveData 源,任何时候最初的 LiveData 源对象改变,MediatorLiveData 的观察者对象被触发。

    原文:

    For example, if you have a LiveData object in your UI that can be updated from a local database or a network, then you can add the following sources to the MediatorLiveData object:

    译文:

    例如,你的 UI 中有一个 LiveData 对象,可以从本地数据库或者网络修改,那么你可以给 MediatorLiveData 对象添加下面的源:

    原文:

    A LiveData object associated with the data stored in the database.
    A LiveData object associated with the data accessed from the network.

    译文:

    一个和存储在数据库中的数据关联的 LiveData 对象。
    一个和来自网络请求的数据关联的 LiveData 对象。

    原文:

    Your activity only needs to observe the MediatorLiveData object to receive updates from both sources. For a detailed example, see the Addendum: exposing network status section of the Guide to App Architecture.

    译文:

    你的 activity 只需要观察 MediatorLiveData 对象接收来自两个源的更新。一个详细的例子见 应用架构指导附录: 暴露网络状态 部分。

    原文:

    Additional resources

    LiveData is an Android Jetpack architecture component. See it in use in the Sunflower demo app.

    译文:

    附加资源

    LiveData 是 Android Jetpack 的一个架构组件,使用 Sunflower 示例应用查看。

    原文:

    For additional information on using LiveData with Snackbar messages, navigation events, and other events, read this post.

    译文:

    LiveData 结合 Snackbar 消息,导航事件及其他事件使用的附加信息,阅读 这篇文章

    相关文章

      网友评论

        本文标题:[翻译]LiveData 概述( LiveData overvi

        本文链接:https://www.haomeiwen.com/subject/hviliftx.html