Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從 MVP 到 MVVM:Android DataBinding 帶來的架構升級

編輯:關於 Android 程式設計

1、DataBinding:再見 MVP,你好 MVVM

談到 Android 應用程式的架構模式,MVP 長期佔據主流地位。Ted Mosby、Nucleus、Mortar 這些框架都採用 Presenter 架構,讓 App 的結構變得清晰,也幫我們解決了一個由來已久的痛點:螢幕旋轉與狀態持久化。嚴格說這不是直接的 MVP 概念,但正是這樣的模型讓我們的程式碼得以解耦。

DataBinding 在 Google I/O 2015 被提出,並在 Android M 預覽版中進入支援庫,號稱「改變一切」。根據 Wikipedia 的描述,MVP 中的 Presenter 承擔這些職責:

Presenter 依據模型與視圖運作。它從儲存庫(模型)中取得資料,並將其格式化為適合在視圖中顯示的形式。

問題就在這裡:DataBinding 框架幾乎取代了 Presenter 的主要職責(也就是在模型與視圖之間搬運、轉換資料),剩下的功能則交給增強版的模型——也就是 ViewModel。ViewModel 是一個標準的 Java 類別,唯一的責任是代表某個 View 中的資料。它可以合併來自多個來源的資料並加以呈現。

把這些拼起來,就得到最終的 MVVM(Model-View-ViewModel)。這個概念最初由微軟在 2005 年提出,別被年份嚇到——它其實很成熟。下面用 Hanne Dorfmann 介紹他的 Ted Mosby 框架時所用的圖,說明從 MVP 到 MVVM 的變化。

所有的資料綁定與更新都交由 DataBinding 框架完成。ObservableField 讓視圖能對模型的變化做出反應,而 XML 中的欄位引用也會反向驅動 ViewModel 的更新。你也可以在程式碼中訂閱變化,例如讓 CheckBox 被勾選時自動停用某個 TextView。

如果有一個標準 Java 類別能完整表示 View 的狀態,好處非常明顯:可測試性大幅提高,因為它不再依賴 Android 框架。

注意 MVP 上圖中有個 Presenter.loadUsers() 的方法呼叫。在 MVVM 模式中,這些方法全部定義在 ViewModel 裡。引用維基百科的說法:

The view model is an abstraction of the view that exposes public properties and commands.

在 MVP 中,你的 Model 很可能是個「笨」的類別,只負責存資料。不要害怕把業務邏輯放進 Model 或 ViewModel——這是物件導向設計的核心原則之一。回到 Presenter.loadUsers():我們不會在 ViewModel 中呼叫這個方法,因為視圖是透過 XML 綁定觸發的。如果不用 DataBinding,我們仍然得回到舊的 Android 語法——android:onClick 屬性,或手動寫監聽器程式碼。

2、處理系統呼叫

仍然有一類工作必須留在 View 裡:初始化系統回呼、開啟 Dialog,或任何涉及 Context 的操作。不要把這些程式碼放進 ViewModel。如果你把 Context 塞進 ViewModel,那就錯了——這會直接摧毀 ViewModel 的可測試性,因為單元測試環境中根本沒有 Context。

我還沒找到完美解法,但有幾種可嘗試的方向。一種是在 View 持有的 ViewModel 中,保留一個 presenter 介面的引用,這樣不會破壞可測試性(測試時注入 mock 實作即可)。另一種是用 event bus 或 Square 的 Otto 這類訊息匯流排機制,例如發出一個 ShowToastMessage("hello world") 事件,由 View 端訂閱並處理。這會讓 View 與 ViewModel 的分離更徹底——但這一定是好事嗎?值得思考。

3、我們還需要框架嗎

那麼 DataBinding 是否取代了其他框架?只有部分。我期待看到的是這些框架演化成 MVVM 風格,讓我們能同時享受 DataBinding 的便利,又把第三方框架的依賴降到最低,保持框架本身小而簡單。

Presenter 時代確實要結束了,剩下真正重要的職責只有生命週期管理與視圖狀態(ViewModel)持久化。有趣的是,這一點到現在為止並沒有太大改變。

我最近了解到 Android ViewModel 框架,它可能相當適合 MVVM 搭配 Android DataBinding 的組合。

4、總結

當我最初聽說 Android M 的所有工作都是為了改進 SDK、關注開發者體驗時,非常振奮。而接觸到 DataBinding 時更是驚訝——我在其他平台上已經寫了很多年資料綁定:WinForms、WPF、Silverlight 和 Windows Phone。我知道這能幫我們寫出更乾淨的架構、耦合更少的程式碼。這個框架是與我們協作,而不是與我們對抗。現在,它終於來了。

但它仍有缺點。事實上,你在 XML 中定義的綁定表達式不參與編譯,也就無法被單元測試覆蓋。這代表許多錯誤會在執行期才爆發,而不是編譯期。更麻煩的是,如果你經常忘記綁定某個 view 呢?

這就是為什麼我希望 Google 能讓 Android Studio 對資料綁定提供完整的語法支援與編譯期檢查、自動補全,以及 XML 欄位的重新命名重構。從我在 Android Studio 1.3 測試版中的使用經驗看,部分功能已支援,還有許多不支援,但我看到了很大的希望。

5、程式碼範例

下面分別用 MVP 與 MVVM 實作同一個畫面。

MVP — VIEW — XML

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivityFragment">

    <TextView
        android:id="@+id/loggedInUserCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="..." />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="false"
        android:layout_toStartOf="@+id/loggedInUserCount"
        android:text="# logged in users:" />

    <RadioGroup
        android:id="@+id/existingOrNewUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:gravity="center"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/returningUserRb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Returning user" />

        <RadioButton
            android:id="@+id/newUserRb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New user" />
    </RadioGroup>

    <LinearLayout
        android:id="@+id/username_block"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/existingOrNewUser"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="100dp"
            android:text="Username:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/password_block"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username_block"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="100dp"
            android:text="Password:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/email_block"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password_block"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="100dp"
            android:text="Email:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textEmailAddress" />
    </LinearLayout>
</RelativeLayout>

MVP — VIEW — JAVA

package com.nilzor.presenterexample;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hannesdorfmann.mosby.mvp.MvpFragment;
import com.hannesdorfmann.mosby.mvp.MvpView;

import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivityFragment extends MvpFragment implements MvpView {

    @InjectView(R.id.username)          TextView mUsername;
    @InjectView(R.id.password)          TextView mPassword;
    @InjectView(R.id.newUserRb)         RadioButton mNewUserRb;
    @InjectView(R.id.returningUserRb)   RadioButton mReturningUserRb;
    @InjectView(R.id.loginOrCreateButton) Button mLoginOrCreateButton;
    @InjectView(R.id.email_block)       ViewGroup mEmailBlock;
    @InjectView(R.id.loggedInUserCount) TextView mLoggedInUserCount;

    public MainActivityFragment() { }

    @Override
    public MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        attachEventListeners();
    }

    private void attachEventListeners() {
        mNewUserRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateDependentViews();
            }
        });
        mReturningUserRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateDependentViews();
            }
        });
    }

    /** Prepares the initial state of the view upon startup */
    public void setInitialState() {
        mReturningUserRb.setChecked(true);
        updateDependentViews();
    }

    /** Shows/hides email field and sets correct text of login button
     *  depending on state of radio buttons */
    public void updateDependentViews() {
        if (mReturningUserRb.isChecked()) {
            mEmailBlock.setVisibility(View.GONE);
            mLoginOrCreateButton.setText(R.string.log_in);
        } else {
            mEmailBlock.setVisibility(View.VISIBLE);
            mLoginOrCreateButton.setText(R.string.create_user);
        }
    }

    public void setNumberOfLoggedIn(int numberOfLoggedIn) {
        mLoggedInUserCount.setText("" + numberOfLoggedIn);
    }

    @OnClick(R.id.loginOrCreateButton)
    public void loginOrCreate() {
        if (mNewUserRb.isChecked()) {
            Toast.makeText(getActivity(), "Please enter a valid email address",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "Invalid username or password",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

MVP — PRESENTER

package com.nilzor.presenterexample;

import android.os.Handler;
import android.os.Message;

import com.hannesdorfmann.mosby.mvp.MvpPresenter;

public class MainPresenter implements MvpPresenter {

    MainModel mModel;
    private MainActivityFragment mView;

    public MainPresenter() {
        mModel = new MainModel();
    }

    @Override
    public void attachView(MainActivityFragment view) {
        mView = view;
        view.setInitialState();
        updateViewFromModel();
        ensureModelDataIsLoaded();
    }

    @Override
    public void detachView(boolean retainInstance) {
        mView = null;
    }

    private void ensureModelDataIsLoaded() {
        if (!mModel.isLoaded()) {
            mModel.loadAsync(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    updateViewFromModel();
                    return true;
                }
            });
        }
    }

    /** Notifies the views of the current value of "numberOfUsersLoggedIn", if any */
    private void updateViewFromModel() {
        if (mView != null && mModel.isLoaded()) {
            mView.setNumberOfLoggedIn(mModel.numberOfUsersLoggedIn);
        }
    }
}

MVP — MODEL

package com.nilzor.presenterexample;

import android.os.AsyncTask;
import android.os.Handler;

import java.util.Random;

public class MainModel {

    public Integer numberOfUsersLoggedIn;
    private boolean mIsLoaded;

    public boolean isLoaded() {
        return mIsLoaded;
    }

    public void loadAsync(final Handler.Callback onDoneCallback) {
        new AsyncTask() {
            @Override
            protected Void doInBackground(Void... params) {
                // 模擬從遠端伺服器非同步取資料
                try { Thread.sleep(2000); } catch (Exception ex) { }
                numberOfUsersLoggedIn = new Random().nextInt(1000);
                mIsLoaded = true;
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                onDoneCallback.handleMessage(null);
            }
        }.execute((Void) null);
    }
}

MVVM — VIEW — XML

注意 <layout> 根標籤、<data> 區塊,以及那些 @{...} 綁定表達式——這三個元素的有無,就是 MVP 與 MVVM 在 XML 層最直觀的差異。

<layout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

    <data>
        <variable name="data" type="com.nilzor.presenterexample.MainModel" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivityFragment">

        <TextView
            android:id="@+id/loggedInUserCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="@{data.numberOfUsersLoggedIn}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toStartOf="@+id/loggedInUserCount"
            android:text="# logged in users:" />

        <RadioGroup
            android:id="@+id/existingOrNewUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp"
            android:gravity="center"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/returningUserRb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="@{data.isExistingUserChecked}"
                android:text="Returning user" />

            <RadioButton
                android:id="@+id/newUserRb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New user" />
        </RadioGroup>

        <LinearLayout
            android:id="@+id/username_block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/existingOrNewUser"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="100dp"
                android:text="Username:"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="200dp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/password_block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/username_block"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="100dp"
                android:text="Password:"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPassword" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/email_block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/password_block"
            android:orientation="horizontal"
            android:visibility="@{data.emailBlockVisibility}">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="100dp"
                android:text="Email:"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textEmailAddress" />
        </LinearLayout>

        <Button
            android:id="@+id/loginOrCreateButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/email_block"
            android:layout_centerHorizontal="true"
            android:text="@{data.loginOrCreateButtonText}" />
    </RelativeLayout>
</layout>

MVVM — VIEW — JAVA

對照 MVP 版本可以發現,updateDependentViews() 與 attachEventListeners() 這兩個方法整組消失了——它們的職責被 XML 綁定與 ViewModel 接手。

package com.nilzor.presenterexample;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.nilzor.presenterexample.databinding.FragmentMainBinding;

public class MainActivityFragment extends Fragment {

    private FragmentMainBinding mBinding;
    private MainModel mViewModel;

    public MainActivityFragment() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        mBinding = FragmentMainBinding.bind(view);
        mViewModel = new MainModel(this, getResources());
        mBinding.setData(mViewModel);
        attachButtonListener();
        return view;
    }

    private void attachButtonListener() {
        mBinding.loginOrCreateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewModel.logInClicked();
            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        ensureModelDataIsLodaded();
    }

    private void ensureModelDataIsLodaded() {
        if (!mViewModel.isLoaded()) {
            mViewModel.loadAsync();
        }
    }

    public void showShortToast(String text) {
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
    }
}

MVVM — VIEWMODEL

這個類別就是原本的 MainModel,但它現在升級成了 ViewModel:屬性改為 ObservableField,並透過 addOnPropertyChangedCallback 自己處理屬性間的依賴關係。showShortToast 那一段則示範了「不得不回呼 View」時該怎麼做——透過 View 傳入的介面呼叫,而不是直接持有 Context。

package com.nilzor.presenterexample;

import android.content.res.Resources;
import android.databinding.ObservableField;
import android.os.AsyncTask;
import android.view.View;

import java.util.Random;

public class MainModel {

    public ObservableField<String>  numberOfUsersLoggedIn    = new ObservableField<>();
    public ObservableField<Boolean> isExistingUserChecked    = new ObservableField<>();
    public ObservableField<Integer> emailBlockVisibility     = new ObservableField<>();
    public ObservableField<String>  loginOrCreateButtonText = new ObservableField<>();

    private boolean mIsLoaded;
    private MainActivityFragment mView;
    private Resources mResources;

    public MainModel(MainActivityFragment view, Resources resources) {
        mView = view;
        mResources = resources;
        // 實務上建議把這層抽成介面以便測試
        setInitialState();
        updateDependentViews();
        hookUpDependencies();
    }

    public boolean isLoaded() {
        return mIsLoaded;
    }

    private void setInitialState() {
        numberOfUsersLoggedIn.set("...");
        isExistingUserChecked.set(true);
    }

    private void hookUpDependencies() {
        isExistingUserChecked.addOnPropertyChangedCallback(
                new android.databinding.Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(android.databinding.Observable sender, int propertyId) {
                updateDependentViews();
            }
        });
    }

    public void updateDependentViews() {
        if (isExistingUserChecked.get()) {
            emailBlockVisibility.set(View.GONE);
            loginOrCreateButtonText.set(mResources.getString(R.string.log_in));
        } else {
            emailBlockVisibility.set(View.VISIBLE);
            loginOrCreateButtonText.set(mResources.getString(R.string.create_user));
        }
    }

    public void loadAsync() {
        new AsyncTask() {
            @Override
            protected Void doInBackground(Void... params) {
                // 模擬從遠端伺服器非同步取資料
                try { Thread.sleep(2000); } catch (Exception ex) { }
                numberOfUsersLoggedIn.set("" + new Random().nextInt(1000));
                mIsLoaded = true;
                return null;
            }
        }.execute((Void) null);
    }

    public void logInClicked() {
        // 說明為何仍需透過可測試的介面回呼 View
        if (isExistingUserChecked.get()) {
            mView.showShortToast("Invalid username or password");
        } else {
            mView.showShortToast("Please enter a valid email address");
        }
    }
}

結語

MVVM 的價值不在於「時髦」,而在於它把可測試的程式碼比例推到了最高:凡是能放進 ViewModel 的邏輯,都變成可以脫離 Android 環境用 JUnit 直接測的普通 Java 程式碼。唯一無法剝離的 Context 相關操作,則被壓縮到 View 的薄薄一層裡。

當然,今天的 Android 開發已經有了更完整的官方方案——ViewModel、LiveData、Flow 與 DataBinding 的雙向綁定,加上 Jetpack 的架構元件,讓本文描述的這套手刻 MVVM 顯得有些原始。但核心思路並未改變:讓 UI 保持被動,讓狀態 own 在一個可測試的類別裡,讓資料流單向流動。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved