[翻譯]LiveData 概述( LiveData overview)

前言:

這是一篇Android官方關(guān)于LiveData介紹的翻譯,正如名字所展示的,它是對存活數(shù)據(jù)的一個封裝類,把網(wǎng)絡請求,數(shù)據(jù)庫查詢或者其他方式得到的數(shù)據(jù)保存在 LiveData 對象中,并且注冊觀察者監(jiān)聽 LiveData 內(nèi)容的變化,當數(shù)據(jù)變化時,更新 UI 組件。是一個觀察者設(shè)計模式的應用。結(jié)合生命周期感知組件,就能在 UI 組件處于活動狀態(tài)時,才會收到 LiveData 數(shù)據(jù)變化的通知,文章中列舉了這種模式的幾點優(yōu)勢。簡單來說,一是把數(shù)據(jù)和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)的數(shù)據(jù)存儲類。不像通常的observable,LiveData 是生命周期感知(lifecycle-aware)的,意味著它遵守其他應用組件的生命周期,例如activities,fragments 或者 services。這種感知確保 LiveData 只會在生命周期在活動狀態(tài)時更新應用組件觀察者。

原文:

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 狀態(tài),則它在活動狀態(tài)。LiveData 只會把相關(guān)更新通知給活動的觀察者。已注冊的非活動狀態(tài)的觀察者不會被通知變化。

原文:

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.

譯文:

你可以注冊一個觀察者,和一個實現(xiàn) LifecycleOwner 接口的對象配對。這種關(guān)系使得當相應的生命周期對象的狀態(tài)變成 DESTROYED 時,觀察者被移出。這對 activities 和 fragments 非常有用,因為他們可以安全地觀察 LiveData,并且不用擔心泄漏,當它們的生命周期是已銷毀(destroyed)時,activities 和 fragments 立即取消訂閱。

原文:

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

譯文:

更多關(guān)于如何使用 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 和你的數(shù)據(jù)狀態(tài)相匹配

LiveData 遵循觀察者模式,當生命周期狀態(tài)變化時,LiveData 通知觀察者(Observer)對象。你可以在這些觀察者對象中整合你更新UI的代碼,而不是應用數(shù)據(jù)每次發(fā)生變化時更新UI。每次有變化時你的觀察者能夠更新UI。

原文:

No memory leaks

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

譯文:

沒有內(nèi)存泄漏

觀察者(Observers ) 被綁定到生命周期(Lifecycle)對象上,當它們所關(guān)聯(lián)的生命周期是已銷毀 (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 組件僅僅觀察相關(guān)的數(shù)據(jù),并且不要停止或者恢復觀察。LiveData 自動管理所有這些,因為在觀察階段它是知道相關(guān)生命周期狀態(tài)變化的。

原文:

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.

譯文:

經(jīng)常更新到最新數(shù)據(jù)

如果一個生命周期變成不活動,直到再次變成活動狀態(tài)它才能收到最新數(shù)據(jù)。例如,一個在后臺的 activity 剛好在回到前臺后會接收最新的數(shù)據(jù)。

原文:

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 因為配置變化而重新創(chuàng)建,例如設(shè)備旋轉(zhuǎn),它立刻能收到最新的可用數(shù)據(jù)。

原文:

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 對象,使用單例模式來包裝系統(tǒng)服務,這樣它們可以在你的APP中共享。LiveData 對象連接一次系統(tǒng)服務,然后任何需要資源的觀察者可以只觀察 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. 創(chuàng)建一個 LiveData 實例來保存一個確定類型的數(shù)據(jù),這通常用你的 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. 創(chuàng)建一個 Observer 對象,它定義了 onChanged() 方法,當 LiveData 對象保存的數(shù)據(jù)變化時這個方法控制發(fā)生了什么。你通常在一個UI控制器里面創(chuàng)建一個 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,并不關(guān)聯(lián) LifecycleOwner 對象,使用 observeForever(Observer) 方法。在這種情形下,observer 被認為是一直活動的,因此總是會被通知變化。你可以調(diào)用 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 對象中的值時,它觸發(fā)所有已注冊的觀察者,如果依附的 LifecycleOwner 在活動狀態(tài)。

原文:

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 對象保存的數(shù)據(jù)發(fā)生變化時,作為回應,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:

譯文:

創(chuàng)建 LiveData 對象

LiveData 是一個包裝器,可以和任何數(shù)據(jù)一起使用,包括實現(xiàn)容器(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 對象中的數(shù)據(jù)沒有設(shè)置。

原文:

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 臃腫?,F(xiàn)在這些 UI 控制器負責顯示數(shù)據(jù),但不保存數(shù)據(jù)狀態(tài)。
從特定的 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) 讀到更多關(guān)于 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 對象

在大多數(shù)情況下,一個應用組件的 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.

譯文:

確保系統(tǒng)不會產(chǎn)生來自一個 activity 或者 fragment 的 onResume() 方法的冗余調(diào)用。

原文:

  • 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 在變成活動狀態(tài)后能盡可能快地有可顯示數(shù)據(jù)。一旦一個應用組件在 STARTED 狀態(tài),它從自己正在觀察的 LiveData 對象收到最近的值,這只會在被觀察的 LiveData 已經(jīng)更新時才會發(fā)生。

原文:

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 只會在數(shù)據(jù)變化時分發(fā)更新,并且只會分發(fā)給活動的觀察者。這個行為的一個例外是,觀察者從不活動狀態(tài)變成活動狀態(tài)時也會收到一個更新。此外,如果觀察者再一次從不活動變成活動,它只收到一個更新,如果自從它最后一次變成活動狀態(tài)時,值已經(jīng)發(fā)生了變化。

原文:

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 作為參數(shù)傳遞給 observe() 方法調(diào)用以后,onChanged() 立刻被調(diào)用并提供了最近存儲在 mCurrentName 中的值,如果 LiveData 還沒在 mCurrentName 中設(shè)置一個值,onChanged() 不會被調(diào)用。

原文:

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 沒有公開可用的方法來更新存儲的數(shù)據(jù),MutableLiveData 類公開地暴露了 setValue(T) 和 postValue(T) 方法,并且如果你需要編輯存儲在一個 LiveData 對象中的值,你必須用這些方法。通常 MutableLiveData 被用在 ViewModel 中而且 ViewModel 只暴露不可變的 LiveData 給觀察者。

譯注:

關(guān)于不可變對象,可以參看 《Effective Java 第二版》的 “Item 15: Minimize mutability”,上面這段話的意思是:Observer 的 onChanged 方法中傳遞的參數(shù)是不可修改的,也就是說,在這個方法中修改參數(shù)的值,是不會影響 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:

譯文:

當你建立起觀察關(guān)聯(lián)以后,你可以更新 LiveData 的值,像下面的示例展示的,當用戶輕點一個按鈕,它會觸發(fā)所有觀察者。

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.

譯文:

例子中調(diào)用 setValue(T) 導致觀察者帶著 John Doe 實參調(diào)用它們的 onChanged()方法。這個例子展示了一個按鈕點擊,但是在多種多樣的情景下可以調(diào)用 setValue() 或者 postValue() 更新 mName ,包括網(wǎng)絡請求的響應,數(shù)據(jù)庫加載完成。一概而論,setValue() 或者 postValue() 調(diào)用會觸發(fā)觀察者并且更新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.

譯文:

注意:你必須在主線程調(diào)用 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 對象,可觀察查詢是數(shù)據(jù)庫訪問對象(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上的數(shù)據(jù)和存儲在數(shù)據(jù)庫中的數(shù)據(jù)保持同步很是有用。你可以在 Room 持久化庫指導 閱讀更多關(guān)于 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 狀態(tài)或者 RESUMED 狀態(tài), LiveData 認為一個觀察者在活動狀態(tài),下面的示例代碼說明如何擴展 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 實現(xiàn)包括下面重要的方法:

  • 當 LiveData 對象有一個活動的觀察者時,onActive() 方法被調(diào)用,這意味著你需要從這個方法開始觀察股票價格變化。
  • 當 LiveData 對象不再有任何活動的觀察者時,onInactive()` 方法被調(diào)用,既然沒有觀察者在監(jiān)聽,也就沒有和 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 實例,作為第一個參數(shù)。這樣做表示這個觀察者被綁定到了和所有者關(guān)聯(lián)的 Lifecycle 對象,意味著:

  • 如果 Lifecycle 對象不在活動狀態(tài),那么即使值發(fā)生了變化,觀察者不會被調(diào)用。
  • 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 中共享它們。為了保持示例簡單,你可以像下面一樣,用一個單例模式實現(xiàn) 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 只在其中一個或者多個處于可見或者活動時連接到系統(tǒng)服務。

原文:

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

你可能想要在分發(fā)給觀察者之前,修改存儲在一個 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 對象中的值應用一個函數(shù),并且向下傳遞結(jié)果。

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對象中的值應用一個函數(shù),解開并且向下分發(fā)結(jié)果,傳遞給 switchMap() 的函數(shù)必須返回一個 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.

譯文:

你可以使用轉(zhuǎn)換方法攜帶信息貫穿觀察者的生命周期。轉(zhuǎn)換不會計算,除非有一個觀察者在監(jiān)視返回的 LiveData 對象。因為轉(zhuǎn)換是延遲計算的,生命周期相關(guān)的行為是隱式傳遞下來的,不需要額外的顯式調(diào)用或者依賴。

原文:

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 對象中需要一個生命周期對象,一個轉(zhuǎn)換或許是更好的解決方案,例如,假設(shè)你有一個 UI 組件接收一個地址,返回這個地址的郵政編碼,你可以給這個組件實現(xiàn)一個簡單的 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 組件每次調(diào)用 getPostalCode() 需要從之前的 LiveData 對象反注冊,然后注冊到新的實例。此外,如果 UI 組件被重新創(chuàng)建,它觸發(fā)另一個 repository.getPostCode() 方法調(diào)用,而不是使用之前的調(diào)用結(jié)果。

原文:

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

譯文:

替代做法是,你可以按照一個輸入地址轉(zhuǎn)換來實現(xiàn)郵政編碼查找,像下面的示例顯示的一樣:

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 的轉(zhuǎn)換定義的,這意味著 repository.getPostCode() 方法在 addressInput 改變時被調(diào)用,當有一個活動的觀察者時時這樣的,如果 repository.getPostCode() 被調(diào)用的時刻還沒有活動的觀察者,沒有計算執(zhí)行,直到一個觀察者被添加進來。

原文:

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.

譯文:

這個機制允許應用下層創(chuàng)建 LiveData 對象,它根據(jù)需要延遲計算,一個 ViewModel 對象可以容易獲取 LiveData 對象的引用,然后在頂層定義它們的轉(zhuǎn)換規(guī)則。

原文:

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.

譯文:

創(chuàng)建新的轉(zhuǎn)換

在你的應用中有很多不同的特定轉(zhuǎn)換可能會很有用,但是默認是沒有提供的。要實現(xiàn)你自己的轉(zhuǎn)換,你可以使用 MediatorLiveData 類,它監(jiān)聽其他 LiveData 對象并且處理它們發(fā)出的事件。MediatorLiveData 正確地傳遞它的狀態(tài)到源 LiveData 對象。了解更多關(guān)于這種模式,查看 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 的觀察者對象被觸發(fā)。

原文:

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 對象,可以從本地數(shù)據(jù)庫或者網(wǎng)絡修改,那么你可以給 MediatorLiveData 對象添加下面的源:

原文:

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

譯文:

一個和存儲在數(shù)據(jù)庫中的數(shù)據(jù)關(guān)聯(lián)的 LiveData 對象。
一個和來自網(wǎng)絡請求的數(shù)據(jù)關(guān)聯(lián)的 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 對象接收來自兩個源的更新。一個詳細的例子見 應用架構(gòu)指導附錄: 暴露網(wǎng)絡狀態(tài) 部分。

原文:

Additional resources

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

譯文:

附加資源

LiveData 是 Android Jetpack 的一個架構(gòu)組件,使用 Sunflower 示例應用查看。

原文:

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

譯文:

LiveData 結(jié)合 Snackbar 消息,導航事件及其他事件使用的附加信息,閱讀 這篇文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容