手把手教你如何一起用 FluxJava 與 RxJava2

想要追上最新的編程潮流嗎障陶?想要導(dǎo)入最新的 Flux 編程方法嗎藐不?這篇文章將手把手的帶你無痛進(jìn)入 Flux 與 RxJava2 結(jié)合的領(lǐng)域匀哄。

這篇是 FluxJava: 給 Java 使用的 Flux 庫 的延續(xù)秦效,會(huì)透過建構(gòu)一個(gè)演示的 Todo App 的過程來說明如何使用 FluxJava,所有演示的源代碼都可以在 Github 上找到涎嚼。

大部份的內(nèi)容其實(shí)都已經(jīng)寫在另一篇中阱州,但考量到有一些性急的朋友對(duì)于要開另外一篇文章,來看與想找的主題無關(guān)的內(nèi)容會(huì)感到不耐法梯,所以在這篇文章中還是會(huì)呈現(xiàn)完整的步驟及相關(guān)的內(nèi)容苔货。

Flux 簡介

為了方便不熟悉 Flux 的讀者,一開始會(huì)先簡短地說明這個(gè)架構(gòu)立哑。以下是借用 Facebook 在 Flux 官網(wǎng)上的原圖:


從圖上可以看到所有箭頭都是單向的夜惭,且形成一個(gè)封閉的循環(huán)。這一個(gè)循環(huán)代表的是數(shù)據(jù)在 Flux 架構(gòu)中流動(dòng)的過程铛绰,整個(gè)流程以 Dispatcher 為集散中心滥嘴。

Action 大多是由與用戶互動(dòng)的畫面控件所發(fā)起,在透過某種 Creator 的方法產(chǎn)生之后被送入 Dispatcher至耻。此時(shí)若皱,已經(jīng)有跟 Dispatcher 注冊(cè)過的 Store 都會(huì)被調(diào)用,并且經(jīng)由預(yù)先在 Store 上定義好的 Method 接收到 Action尘颓。Store 會(huì)在這個(gè)接收到 Action 的 Method 中走触,將數(shù)據(jù)的狀態(tài)依照 Action 的內(nèi)容來進(jìn)行調(diào)整。

前端的畫面控件或是負(fù)責(zé)控制畫面的控件疤苹,會(huì)收到由 Store 在處理完數(shù)據(jù)后所送出的異動(dòng)事件互广,異動(dòng)的事件就是用來代表在數(shù)據(jù)層的數(shù)據(jù)狀態(tài)已經(jīng)不一樣了。這些前端控件在自行訂義的事件處理方法中聆聽卧土、截收這些事件惫皱,并且在事件收到后由 Store 獲取最新的數(shù)據(jù)狀態(tài)。最后前端控件觸發(fā)自己內(nèi)部的更新畫面程序尤莺,讓畫面上所有階層子控件都能夠反應(yīng)新的數(shù)據(jù)狀態(tài)旅敷,如此完成一個(gè)數(shù)據(jù)流動(dòng)的循環(huán)。

以上是一個(gè)很簡單的說明颤霎,如果需要了解更進(jìn)一步的內(nèi)容媳谁,可以自行上網(wǎng)搜尋,現(xiàn)在網(wǎng)絡(luò)上應(yīng)該已經(jīng)有為數(shù)不少的文章可以參考友酱。

更多深入的文章請(qǐng)參閱簡書 http://www.reibang.com/u/fea63707e07fwznote.blogspot.com

以 BDD 來做為需求的開端

為了能夠更清楚的說明源代碼的細(xì)節(jié)晴音,所以文章中會(huì)依照 BDD 的概念來逐步解說源代碼。所以首先是要先列出需求:

  • 顯示 Todo 清單
  • 在不同用戶間切換 Todo 清單
  • 新增 Todo
  • 關(guān)閉/重啟 Todo

接著下來就要把需求轉(zhuǎn)更明確的敘述內(nèi)容缔杉,因?yàn)橹皇茄菔敬冈辏袃H做出一個(gè) Story 做為目標(biāo):

Story: Manage todo items

Narrative:
As a user
I want to manage todo items
So I can track something to be done


Scenario 1: Add a todo
When I tap the add menu on main activity
Then I see the add todo screen

When I input todo detail and press ADD button
Then I see a new entry in list


Scenario 2: Add a todo, but cancel the action
When I tap the add menu on main activity
 And I press cancel button
Then Nothing happen


Scenario 3: Switch user
When I select a different user
Then I see the list changed


Scenario 4: Mark a todo as done
When I mark a todo as done
Then I see the todo has a check mark and strike through on title

也因?yàn)橹皇茄菔居茫琒tory 的內(nèi)容并沒有很嚴(yán)謹(jǐn)或详,而演示所使用的文字雖然是英文系羞,但在實(shí)際的案例上用自己習(xí)慣的文字即可加缘。

決定測試的方略

既然是采用 BDD 來做演示,當(dāng)然在程序編寫的過程中會(huì)希望能夠有適切的工具的輔助觉啊,畢竟工欲善其事、必先利其器沈贝。所以在編寫測試源代碼時(shí)杠人,不使用 Android 范本中的 JUnit,改為使用在“使用 Android Studio 開發(fā) Web 程序 - 測試”提到的 Spock Framework宋下,并且全部以 Groovy 來編寫嗡善。因?yàn)?Spock Framework 內(nèi)置了支援 BDD 的功能,把之前做好的 Story 轉(zhuǎn)成測試源代碼的工作也會(huì)簡化很多学歧。

接下來要決定如何在 Android 項(xiàng)目中定位與分配測試源代碼罩引。Espresso 是 Android 開發(fā)環(huán)境中內(nèi)置的,使用 Espresso 來開發(fā)測試程序還是有一定的必要性枝笨。只不過 Espresso 必須要跑在實(shí)機(jī)或模擬的環(huán)境上袁铐,運(yùn)行效率問題是無法被忽視的一個(gè)因素,而且 androidTest 下的源代碼其運(yùn)行結(jié)果也沒有辦法在 Android Studio 中檢視 Code Coverage 的狀態(tài)横浑,所以用 Espresso 編寫的測試程序并不適合用來做為 Unit Test剔桨。

再加上新版的 Android Studio 提供了錄制測試步驟的功能,最后會(huì)被轉(zhuǎn)成 Espresso 的源代碼徙融。所以看起來 Espresso 比較適合用來做為開發(fā)程流后段的一些測試工作洒缀,像是 UAT、壓力測試欺冀、穩(wěn)定度測試树绩。依據(jù)這樣的定位,之前寫好的 Story 會(huì)在 Espresso 上轉(zhuǎn)成測試源代碼隐轩,來驗(yàn)證程序的功能是否有達(dá)到 Story 描述的內(nèi)容饺饭。

單元測試的部份沒有疑問地應(yīng)該是寫在 Android 項(xiàng)目范本所提供的 test 的路徑之下,要解決的是 Android 組件如何在 JVM 的環(huán)境中運(yùn)行測試职车。大部份人目前的選擇應(yīng)該都會(huì)是 Robolectric砰奕,只不過測試源代碼要使用 Spock 來開發(fā),所以這二個(gè)包必須要做個(gè)整合提鸟。RoboSpock就是提供此一解決方案的包军援,可以讓 Robolectric 在基于 Spock 所開發(fā)的 Class 中能夠被直接使用。

使用 Robolectric 雖然能夠?qū)?Android 組件在 JVM 中進(jìn)行測試称勋,但畢竟這類的組件相互之間的藕合性還是有點(diǎn)高胸哥,尤其是提供畫面的控件。所以這個(gè)部分在歸類上我定位成 Integration Test赡鲜,但在數(shù)據(jù)的供給上空厌,拜 Flux 架構(gòu)之賜庐船,可以依照情境來進(jìn)行代換,只測試 Android 組件與組件之間的整合度嘲更,這個(gè)部份在接下來的內(nèi)容會(huì)進(jìn)行說明筐钟。附帶一提,有關(guān)測試上的一些想法我有寫成一篇文章赋朦,可以參考:“軟件測試雜談”篓冲。

以下列出本次使用的測試組件清單:

  • Groovy
  • Spock Framework
  • RoboSpock
  • Espresso

設(shè)定 Spock 與 Espresso、Robolectric 時(shí)會(huì)有一些細(xì)節(jié)需要注意宠哄,相關(guān)的說明請(qǐng)參考“配置 build.gradle 來用 Spock 對(duì) Android 組件進(jìn)行測試”壹将。最后的 build.gradle 設(shè)定結(jié)果,可以在 Github 上的文件內(nèi)容中看到毛嫉。

建立畫面配置

在產(chǎn)生完 Android 項(xiàng)目空殼后诽俯,首先修改 MainActivity 的內(nèi)容。在 MainActivity 畫面中加上 RecyclerView 及 Spinner 來顯示 Todo 清單以及提供切換用戶的功能承粤。Layout 的配置顯示如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    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"
    android:orientation="vertical"
    tools:context="com.example.fluxjava.rx.MainActivity">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="LinearLayoutManager"
        tools:listitem="@layout/item_todo" />

</LinearLayout>

開發(fā) UAT

原本范本中默認(rèn)產(chǎn)生的 androidTest/java 的路徑可以刪除暴区,另外要在 androidTest 之下增加一個(gè) groovy 的文件夾,如果 build.gradle 有設(shè)定正確辛臊,在 groovy 文件夾上應(yīng)該會(huì)出現(xiàn)代表測試源代碼的底色颜启。因?yàn)槟壳爸挥幸粋€(gè) Story 所以在 groovy 路徑下配對(duì)的 Package 中增加一個(gè) ManageTodoStory.groovy 的文件。

在這里就可以顯現(xiàn) Spock 所帶來的優(yōu)勢浪讳,把之前的 Story 內(nèi)容轉(zhuǎn)成以下的源代碼缰盏,與原本的 Story 比對(duì)并沒有太大的差距。

@Title("Manage todo items")
@Narrative("""
As a user
I want to manage todo items
So I can track something to be done
""")
class ManageTodoStory extends Specification {

    def "Add a todo"() {
        when: "I tap the add menu on main activity"
        then: "I see the add todo screen"

        when: "I input todo detail and press ADD button"
        then: "I see a new entry in list"
    }

    def "Add a todo, but cancel the action"() {
        when: "I tap the add menu on main activity"
        and: "I press cancel button"
        then: "Nothing happen"
    }

    def "Switch user"() {
        when: "I select a different user"
        then: "I see the list changed"
    }

    def "Mark a todo as done"() {
        when: "I mark a todo as done"
        then: "I see the todo has a check mark and strike through on title"
    }
}

如果 Story 是用中文寫成的淹遵,以上的套用方式還是適用的口猜。有關(guān) Spock 的使用方式在這里就不詳細(xì)地說明,各位可以自行上網(wǎng)搜尋透揣,或是參考我之前寫的這一篇這一篇有關(guān) Spock 的文章济炎。接著就是把源代碼填入,完成后的內(nèi)容如下所示:

@Title("Manage todo items")
@Narrative("""
As a user
I want to manage todo items
So I can track something to be done
""")
class ManageTodoStory extends Specification {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class)
    private RecyclerView mRecyclerView

    def "Add a todo"() {
        when: "I tap the add menu on main activity"
        this.mRecyclerView = (RecyclerView)this.mActivityRule.activity.findViewById(R.id.recyclerView)
        onView(withId(R.id.add)).perform(click())

        then: "I see the add todo screen"
        onView(withText(R.string.dialog_title))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withText(R.string.title))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withId(R.id.title))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withText(R.string.memo))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withId(R.id.memo))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withText(R.string.due_date))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withId(R.id.dueText))
                .inRoot(isDialog())
                .check(matches(isDisplayed()))
        onView(withId(android.R.id.button1))
                .inRoot(isDialog())
                .check(matches(withText(R.string.add)))
                .check(matches(isDisplayed()))
        onView(withId(android.R.id.button2))
                .inRoot(isDialog())
                .check(matches(withText(android.R.string.cancel)))
                .check(matches(isDisplayed()))

        when: "I input todo detail and press ADD button"
        onView(withId(R.id.title))
                .perform(typeText("Test title"))
        onView(withId(R.id.memo))
                .perform(typeText("Sample memo"))
        onView(withId(R.id.dueText))
                .perform(typeText("2016/1/1"), closeSoftKeyboard())
        onView(withId(android.R.id.button1)).perform(click())

        then: "I see a new entry in list"
        onView(withText(R.string.dialog_title))
                .check(doesNotExist())
        this.mRecyclerView.getAdapter().itemCount == 5
        onView(withId(R.id.recyclerView)).perform(scrollToPosition(4))
        onView(withId(R.id.recyclerView))
                .check(matches(hasDescendant(withText("Test title"))))
    }

    def "Add a todo, but cancel the action"() {
        when: "I tap the add menu on main activity"
        this.mRecyclerView = (RecyclerView)this.mActivityRule.activity.findViewById(R.id.recyclerView)
        onView(withId(R.id.add)).perform(click())

        and: "I press cancel button"
        onView(withId(android.R.id.button2)).perform(click())

        then: "Nothing happen"
        this.mRecyclerView.getAdapter().itemCount == 4
    }

    def "Switch user"() {
        when: "I select a different user"
        this.mRecyclerView = (RecyclerView)this.mActivityRule.activity.findViewById(R.id.recyclerView)
        onView(withId(R.id.spinner)).perform(click())
        onView(allOf(withText("User2"), isDisplayed()))
                .perform(click())

        then: "I see the list changed"
        this.mRecyclerView.getAdapter().itemCount == 5
    }

    def "Mark a todo as done"() {
        when: "I mark a todo as done"
        TextView target

        this.mRecyclerView = (RecyclerView)this.mActivityRule.activity.findViewById(R.id.recyclerView)
        onView(withRecyclerView(R.id.recyclerView).atPositionOnView(2, R.id.closed))
                .perform(click())
        target = (TextView)this.mRecyclerView
                .findViewHolderForAdapterPosition(2)
                .itemView
                .findViewById(R.id.title)

        then: "I see the todo has a check mark and strike through on title"
        target.getText().toString().equals("Test title 2")
        (target.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) > 0
    }

    static RecyclerViewMatcher withRecyclerView(final int recyclerViewId) {
        return new RecyclerViewMatcher(recyclerViewId)
    }

}

以上源代碼中使用到的資源當(dāng)然是要在編寫之前就事件準(zhǔn)備好辐真,否則出現(xiàn)錯(cuò)誤的訊息须尚。完成后先運(yùn)行一次測試,當(dāng)然結(jié)果都是失敗的侍咱,接下來就可以依照需求來逐項(xiàng)開發(fā)功能耐床。

了解 RxBus

除了原本 IFluxBus 所定義的 Method 以外,為了善用 RxJava 所帶來的優(yōu)勢楔脯,RxBus 提供一個(gè) toObservable 的 Method撩轰,利用這個(gè) Method 所傳回的 Object,可以進(jìn)行所有 RxJava 所提供的功能。

同時(shí)堪嫂,在向 Observable 訂閱時(shí)會(huì)取得 Subscription偎箫,RxBus 可以協(xié)助管理 Subscription。在 Subscriber 向 RxBus 取消注冊(cè)時(shí)皆串,一并更新所屬的 Subscription 狀態(tài)淹办,以避免持續(xù)地收到通知。

如果是透過 registerunregister 來注冊(cè) Subscriber恶复,則不需要特別處理 Subscription 的問題怜森。但如果是由先前所提到 toObservable 的 Method 來訂閱,則另外要呼叫 addSubscriptionremoveSubscription 來將 Subscription 列入與移除 RxBus 的管理機(jī)制寂玲。

因應(yīng) RxJava2 新的設(shè)計(jì),RxBus 也提供了 toFlowable 的 Method梗摇,用來取得有背壓版本的 Observable拓哟。當(dāng)然,要透過 toObservable 再轉(zhuǎn)換為 Flowable 也行伶授,toFlowable 就只是做為提供一個(gè)便利断序、縮減程式碼的用途。

準(zhǔn)備 Model

這里的 Model 是二個(gè) POJO糜烹,分別用來代表一筆 User 和 Todo 的數(shù)據(jù)內(nèi)容违诗。因?yàn)檫@部分并不是示范的重點(diǎn),所以文件的內(nèi)容請(qǐng)自行參考 User.javaTodo.java疮蹦。

定義常量

常量主要的作用是以不同的數(shù)值來區(qū)分不同的數(shù)據(jù)種類诸迟,以及每一個(gè)數(shù)據(jù)種類因應(yīng)需求所必須提供的功能。如同以下所展示的源代碼內(nèi)容:

// constants for data type
public static final int DATA_USER = 10;
public static final int DATA_TODO = 20;

// constants for actions of user data
public static final int USER_LOAD = DATA_USER + 1;

// constants for actions of todo data
public static final int TODO_LOAD = DATA_TODO + 1;
public static final int TODO_ADD = DATA_TODO + 2;
public static final int TODO_CLOSE = DATA_TODO + 3;

在需求中提到需要處理二種類型的數(shù)據(jù)愕乎,所以就分別定義了 DATA_USERDATA_TODO 來代表用戶及 Todo阵苇。以 User 的需求來看,在畫面上只會(huì)有載入數(shù)據(jù)的要求感论,以提供切換用戶的功能绅项,所以 User 的動(dòng)作只定義了 USER_LOAD。而 Todo 的需求就比較復(fù)雜比肄,除了載入數(shù)據(jù)以外快耿,還要可以新增、關(guān)閉 Todo芳绩。所以目前定義 TODO_LOAD掀亥、TODO_ADDTODO_CLOSE 等三個(gè)常量妥色。

這些常量接下來會(huì)被用在 StoreMap 的鍵值及 Action 的 Type铺浇。在 FluxJava 中并沒有限定只能使用數(shù)值型別來做為鍵值,可以根據(jù)每個(gè)項(xiàng)目的特性來設(shè)定,可以是字串鳍侣、型別或是同一個(gè)型別不同的 Instance丁稀。

編寫 Action 及 Store

UserAction 和 TodoAction 都是很直接地繼承自 FluxAction。其中比較特別是:考量到一次可能會(huì)要處理多筆數(shù)據(jù)倚聚,所以在 Data 屬性的泛型上使用 List 來做為承載數(shù)據(jù)的基礎(chǔ)线衫。這二個(gè) Class 的內(nèi)容請(qǐng)直接連上 Github 的 UserAction.javaTodoAction.java 二個(gè)文件查詢。

Store 可以繼承 FluxJava 內(nèi)置的 RxStore惑折,在 RxStore 中 registerunregister 是提供給前端的畫面元件授账,做為向 Store 登記要接收到資料異動(dòng)事件之用。與 RxBus 相同惨驶,RxStore 額外提供一個(gè) toObservable白热,如果想要取得更多在使用 RxJava 上的彈性,可以改為使用 toObservable粗卜。

當(dāng)外部所有的調(diào)用都是使用 toObservable 來進(jìn)行訂閱屋确,則不會(huì)使用到 IRxDataChange 的 Interface,這個(gè)介面是透過 register 訂閱時(shí)才會(huì)需要實(shí)作续扔。

附帶一提攻臀,與 RxBus 相同,RxStore 也有提供 toFlowable 用來取得有背壓版本的 Observable纱昧,使用的方式與 RxBus 相同刨啸。

Tag 則是考量到同一個(gè) Store 有可能要產(chǎn)生多個(gè) Instance 來服務(wù)不同的畫面控件,所以仿照 Android 控件的方式识脆,用 Tag 來識(shí)別不同的 Instance设联。像是在同一個(gè)畫面中,可能會(huì)因?yàn)樾枨蟮年P(guān)系灼捂,要使用不同條件所產(chǎn)生的清單來呈現(xiàn)圖表仑荐。這時(shí)就有必要使用二個(gè)不同的 Instance 來提供數(shù)據(jù),否則會(huì)造成畫面上數(shù)據(jù)的混亂纵东。

至于 getItem粘招、findItemgetCount 都是很基本在呈現(xiàn)數(shù)據(jù)內(nèi)容時(shí)需要使用到的功能偎球。其中 getItem 之所以限定一次只取得一筆數(shù)據(jù)洒扎,而不是以 List 的方式傳回,主要是為了符合 Flux 單向數(shù)據(jù)流的精神衰絮。如果 getItem 傳回的是 List袍冷,前端很有可能意外地異動(dòng)了清單的內(nèi)容,根據(jù) Java 的特性猫牡,這樣的異動(dòng)結(jié)果也會(huì)反應(yīng)在 Store 所提供的信息上胡诗。也就等于數(shù)據(jù)的清單在 Store 以外,也有機(jī)會(huì)被異動(dòng),這就違反了 Flux 在設(shè)計(jì)上所想要達(dá)成的數(shù)據(jù)流動(dòng)過程煌恢。

當(dāng)然骇陈,就算是只提供一項(xiàng)數(shù)據(jù),前端也許改不了整個(gè)清單瑰抵,但還是可以修改所收到的這單一項(xiàng)目你雌,其結(jié)果一樣會(huì)反應(yīng)回 Store 的內(nèi)部。所以在示范的源代碼中二汛,在 getItem 所傳回的是一個(gè)全新的 Instance婿崭。

@Override
public User getItem(final int inIndex) {
    return new User(this.mList.get(inIndex));
}

在 RxStore 中有一個(gè)關(guān)鍵的 Method 是要覆寫的,那就是 onAction肴颊,是用來接收前端所推送出來的 Action氓栈。而覆寫 getActionType 可以用來指定特定的 Action 型別,避免收到不相關(guān)的 Action 通知婿着。以 UserStore 為例授瘦,會(huì)有以下的內(nèi)容:

@Override
protected <TAction extends IFluxAction> void onAction(TAction inAction) {
    final UserAction action = (UserAction)inAction;

    // base on input action to process data
    // in this sample only define one action
    switch (action.getType()) {
        case USER_LOAD:
            this.mList.clear();
            this.mList.addAll(action.getData());
            super.emitChange(new ListChangeEvent());
            break;
    }
}

可以看到之前定義的常量在這里派上用場了,利用 Action 的 Type 可以區(qū)分出前端所接收到的指令祟身。在這個(gè) Demo 中奥务,Store 的定位只是用來管理清單物独,清單的數(shù)據(jù)會(huì)由 ActionCreator 傳入袜硫,所以可以看到源代碼中只是做很簡單的載入工作,載入完即發(fā)出數(shù)據(jù)異動(dòng)的事件挡篓。這個(gè)事件是定義在 Store 內(nèi)部婉陷,每個(gè) Store 都有定義自己的 Event,以便讓前端控件判別與過濾所想收到的 Event 種類官研。

在以上的 Method 源代碼中秽澳,使用了 RxStore 所提供的功能,在接收到 Action 的當(dāng)下是以背景的 Thread 在運(yùn)行戏羽,避免因?yàn)檫^長的數(shù)據(jù)處理時(shí)間導(dǎo)至前端畫面凍結(jié)担神。Method 的參數(shù)則是用以過濾 Action,讓指定的 Action 型別在 Bus 中被傳遞時(shí)才調(diào)用 Mehtod始花,減少源代碼判斷上的負(fù)擔(dān)妄讯。如果是同一個(gè) Store 有多個(gè) Instace 同時(shí)存在,在接收到的 Action 中可以加入 Tag 的信息酷宵,以便讓 Store 判別目前傳入的 Action 是否為針對(duì)自己所發(fā)出來的亥贸。

而因?yàn)樾枨蟮年P(guān)系,同樣的 Method 在 TodoStore 中就相對(duì)地復(fù)雜了一點(diǎn):

@Override
protected <TAction extends IFluxAction> void onAction(final TAction inAction) {
    final TodoAction action = (TodoAction)inAction;

    // base on input action to process data
    switch (action.getType()) {
        case TODO_LOAD:
            this.mList.clear();
            this.mList.addAll(action.getData());
            super.emitChange(new ListChangeEvent());
            break;
        case TODO_ADD:
            this.mList.addAll(action.getData());
            super.emitChange(new ListChangeEvent());
            break;
        case TODO_CLOSE:
            for (int j = 0; j < action.getData().size(); j++) {
                for (int i = 0; i < this.mList.size(); i++) {
                    if (this.mList.get(i).id == action.getData().get(j).id) {
                        this.mList.set(i, action.getData().get(j));
                        super.emitChange(new ItemChangeEvent(i));
                        break;
                    }
                }
            }
            break;
    }
}

主要是多了二種數(shù)據(jù)處理的要求:在新增時(shí)浇垦,前端會(huì)把新增的內(nèi)容傳入炕置,所以這里很簡單地把收到的項(xiàng)目加入清單之中,就可以通知前端更新數(shù)據(jù)。至于在關(guān)閉 Todo 的部份朴摊,由于之前提到 Store 在 getItem 回傳的都是全新的 Instance默垄,所以要先進(jìn)行比對(duì)找出數(shù)據(jù)在清單中的位置,因?yàn)槭鞘痉兜木壒嗜耘軉渭兊刂粚懥藗€(gè)循環(huán)來比對(duì)厕倍。找到了對(duì)應(yīng)的位置后,直接以新的內(nèi)容取代原本清單中的項(xiàng)目贩疙,再通知前端更新畫面讹弯。

如此,Action 與 Store 的編寫工作就算完成了这溅。同樣地组民,在這個(gè)階段的最后,運(yùn)行寫好的測試程序來確認(rèn)目前為止的工作成果悲靴。

編寫 ActionHelper

FluxJava 已經(jīng)內(nèi)置了一個(gè)負(fù)責(zé) ActionCreator 的 Class臭胜,這個(gè) ActionCreator 使用 ActionHelper 來注入自定義的程序邏輯●校可自定義的內(nèi)容分為二個(gè)部份耸三,第一個(gè)是決定如何建立 Action 的 Instance,第二個(gè)是協(xié)助處理數(shù)據(jù)格式的轉(zhuǎn)換浇揩。

以下是第一個(gè)部份的演示源代碼:

public Class<?> getActionClass(final Object inActionTypeId) {
    Class<?> result = null;

    if (inActionTypeId instanceof Integer) {
        final int typeId = (int)inActionTypeId;

        // return action type by pre-define id
        switch (typeId) {
            case USER_LOAD:
                result = UserAction.class;
                break;
            case TODO_LOAD:
            case TODO_ADD:
            case TODO_CLOSE:
                result = TodoAction.class;
                break;
        }
    }

    return result;
}

內(nèi)容的重點(diǎn)就是依照先前定義好的常量來指定所屬的 Action 型別仪壮。

第二個(gè)部分就會(huì)有比較多的工作需要完成:

public Object wrapData(final Object inData) {
    Object result = inData;

    // base on data type to convert data into require form
    if (inData instanceof Integer) {
        result = this.getRemoteData((int)inData, -1);
    }
    if (inData instanceof String) {
        final String[] command = ((String)inData).split(":");
        final int action;
        final int position;

        action = Integer.valueOf(command[0]);
        position = Integer.valueOf(command[1]);
        result = this.getRemoteData(action, position);
    }
    if (inData instanceof Todo) {
        final ArrayList<Todo> todoList = new ArrayList<>();

        this.updateRemoteTodo();
        todoList.add((Todo)inData);
        result = todoList;
    }

    return result;
}

根據(jù) Flux 文件的說明,ActionCreator 在建立 Action 的時(shí)候是調(diào)用外部 API 取得數(shù)據(jù)的切入點(diǎn)胳徽。所以 ActionHelper 提供了一個(gè) wrapData 來讓使用 FluxJava 的程序有機(jī)會(huì)在此時(shí)取得外部的數(shù)據(jù)积锅。在以上的程序中,還另外演示了另一種 wrapData 可能的用途养盗。由于在前端會(huì)接收到的信息有可能有多種變化缚陷,像是在演示中,要求載入 User 時(shí)只需要一個(gè)數(shù)值往核、在載入 Todo 時(shí)則要額外告知此時(shí)選擇的 User箫爷、在新增或修改 Todo 時(shí)則是要把修改的結(jié)果傳入。這時(shí) wrapData 就可以適時(shí)地把這些不同型式的信息轉(zhuǎn)成 Store 要的內(nèi)容放在 Action 中聂儒,讓 Store 做后續(xù)的處理虎锚。

如果想要使用自定義的 ActionCreator,可以在初始化 FluxContext 時(shí)將自定義的 ActionCreator Instance 傳入薄货,只是這個(gè)自定義的 ActionCreator 要繼承自內(nèi)置的 ActionCreator翁都,以覆寫原本的 Method 來達(dá)到自定義的效果。

組合控件

這次演示中谅猾,F(xiàn)lux 的架構(gòu)橫跨整個(gè) App 的生命周期柄慰。所以最合理的切入位置是自定義的 Application鳍悠,這里增加了一個(gè)名為 AppConfig 的 Class 做為初始化 Flux 架構(gòu)的進(jìn)入點(diǎn),同時(shí)修改 AndroidManifest.xml 讓 AppConfig 可以在 App 啟動(dòng)時(shí)被調(diào)用坐搔。

在 AppConfig 內(nèi)增加一個(gè) setupFlux 的 Method藏研,內(nèi)容如下:

private void setupFlux() {
    HashMap<Object, Class<?>> storeMap = new HashMap<>();

    storeMap.put(DATA_USER, UserStore.class);
    storeMap.put(DATA_TODO, TodoStore.class);

    // setup relationship of components in framework
    FluxContext.getBuilder()
            .setBus(new Bus())
            .setActionHelper(new ActionHelper())
            .setStoreMap(storeMap)
            .build();
}

重點(diǎn)工作是把之前步驟中準(zhǔn)備好的 Bus、ActionHelper概行、StoreMap 傳入 FluxContext 的 Builder 之中蠢挡,并且透過 Builder 建立 FluxContext 的 Instance。截至目前為止凳忙,后端準(zhǔn)備的工作算是完成了业踏,在文件夾的結(jié)構(gòu)上各位應(yīng)該可以看出來,我把以上的 Class 都?xì)w類在 Domain 的范疇之中涧卵。

編寫 Adapter

Adapter 是用來供給 Spinner 及 RecyclerView 數(shù)據(jù)的 Class勤家,同時(shí)在這次的演示中也是與 FluxJava 介接的關(guān)鍵角色,代表的是在 Flux 流程圖中的 View柳恐。在 MainActivity 中 Spinner 是用來顯示 User 清單伐脖,而 RecyclerView 是用來顯示 Todo 清單寿烟,所以各自對(duì)應(yīng)的 Adapter 分別是 UserAdapter 及 TodoAdapter搞隐。

雖然這二個(gè) Adapter 繼承自不同的 Base Class,但是都需要提供 Item 的 Layout 以便展示數(shù)據(jù)做祝。所以先產(chǎn)生 item_user.xmlitem_todo.xml 二個(gè)文件近尚。

準(zhǔn)備好了 Item 的 Layout 就可以進(jìn)行 Adapter 的編寫工作蠕啄,以下是 UserAdapter 的完整內(nèi)容:

public class UserAdapter extends BaseAdapter {

    private UserStore mStore;

    public UserAdapter() {
        // get the instance of store that will provide data
        this.mStore = (UserStore)FluxContext.getInstance().getStore(DATA_USER, null, null);
        this.mStore.toObservable(UserStore.ListChangeEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<UserStore.ListChangeEvent>() {
                            @Override
                            public void accept(final UserStore.ListChangeEvent inEvent) throws Exception {
                                UserAdapter.super.notifyDataSetChanged();
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(final Throwable inThrowable) throws Exception {
                                // put error handle here
                            }
                        });
    }

    @Override
    public int getCount() {
        return this.mStore.getCount();
    }

    @Override
    public Object getItem(final int inPosition) {
        return this.mStore.getItem(inPosition);
    }

    @Override
    public long getItemId(final int inPosition) {
        return inPosition;
    }

    @Override
    public View getView(final int inPosition, final View inConvertView, final ViewGroup inParent) {
        View itemView = inConvertView;

        // bind data into item view of Spinner
        if (itemView == null) {
            itemView = LayoutInflater
                    .from(inParent.getContext())
                    .inflate(R.layout.item_user, inParent, false);
        }

        if (itemView instanceof TextView) {
            ((TextView)itemView).setText(this.mStore.getItem(inPosition).name);
        }

        return itemView;
    }

    public void dispose() {
        // Clear object reference to avoid memory leak issue
        FluxContext.getInstance().unregisterStore(this.mStore, this);
    }

}

在 UserAdapter 的 Constructor 中,使用 FluxContext 來取得 Store 的 Instance肿男。使用的第一個(gè)參數(shù)就是之前在常量定義好的 USER_DATA介汹,第二參數(shù)的 Tag 因?yàn)楸敬问痉稕]有使用到所以傳入 Null却嗡。最后一個(gè)參數(shù)是把 Adapter 本身的 Instance 傳入舶沛,F(xiàn)luxContext 會(huì)把傳入的 Instance 注冊(cè)到 Store 中。當(dāng)然窗价,如果要在取回 Store 后再自行注冊(cè)也是可以的如庭。

之后部份就是 Adapter 的基本應(yīng)用,需要提供數(shù)據(jù)有關(guān)的信息時(shí)撼港,則是透過 Store 來取得坪它。

在 Adapter 的 Constructor 中可以看到以 RxJava 的方式向 Store 進(jìn)行訂閱的程序,可以用來接收資料異動(dòng)的事件帝牡。傳入的 Action 型別參數(shù)是用來限定要收到的事件種類往毡,被呼叫后的工作也很簡單,就是轉(zhuǎn)通知 Spinner 重刷畫面靶溜。由于是要更新畫面上的資訊开瞭,所以要回到 UI Thread 來執(zhí)行懒震,observeOn 被指定為 MainThread。如果同一個(gè) Store 同時(shí)有多個(gè) Instance 存在嗤详,和 Store 的 onAction 一樣个扰,可以在 Event 中加入 Tag 的資訊,以減少無用的重刷頻繁地出現(xiàn)葱色。

最后則是一個(gè)用來釋放 Reference 的接口递宅,主要之目的是避免 Memory Leak 的問題,大部份都是在 Activity 卸載時(shí)調(diào)用苍狰。

以下是另外一個(gè) Adapter - TodoAdapter 的內(nèi)容:

public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.ViewHolder> {

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        TextView dueDate;
        TextView memo;
        CheckBox closed;

        ViewHolder(final View inItemView) {
            super(inItemView);
            this.title = (TextView)inItemView.findViewById(R.id.title);
            this.dueDate = (TextView)inItemView.findViewById(R.id.dueDate);
            this.memo = (TextView)inItemView.findViewById(R.id.memo);
            this.closed = (CheckBox)inItemView.findViewById(R.id.closed);
        }
    }

    private TodoStore mStore;

    public TodoAdapter() {
        // get the instance of store that will provide data
        this.mStore = (TodoStore)FluxContext.getInstance().getStore(DATA_TODO, null, null);
        this.mStore.toObservable(TodoStore.ListChangeEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<TodoStore.ListChangeEvent>() {
                            @Override
                            public void accept(final TodoStore.ListChangeEvent inEvent) throws Exception {
                                TodoAdapter.super.notifyDataSetChanged();
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(final Throwable inThrowable) throws Exception {
                                // put error handle here
                            }
                        });
        this.mStore.toObservable(TodoStore.ItemChangeEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<TodoStore.ItemChangeEvent>() {
                            @Override
                            public void accept(final TodoStore.ItemChangeEvent inEvent) throws Exception {
                                TodoAdapter.super.notifyItemChanged(inEvent.position);
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(final Throwable inThrowable) throws Exception {
                                // put error handle here
                            }
                        });
    }

    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup inParent, final int inViewType) {
        final View itemView = LayoutInflater
                .from(inParent.getContext()).inflate(R.layout.item_todo, inParent, false);

        // use custom ViewHolder to display data
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder inViewHolder, final int inPosition) {
        final Todo item = this.mStore.getItem(inPosition);

        // bind data into item view of RecyclerView
        inViewHolder.title.setText(item.title);
        inViewHolder.dueDate.setText(item.dueDate);
        inViewHolder.memo.setText(item.memo);
        inViewHolder.closed.setOnCheckedChangeListener(null);
        inViewHolder.closed.setChecked(item.closed);
    }

    @Override
    public int getItemCount() {
        return this.mStore.getCount();
    }

    public void dispose() {
        // Clear object reference to avoid memory leak issue
        FluxContext.getInstance().unregisterStore(this.mStore, this);
    }

}

除了因?yàn)槭抢^承自不同 Base Class 所產(chǎn)生的寫法上之差異外办龄,并沒有太大的不同。重點(diǎn)是在接收事件的訂閱多了一個(gè)淋昭,用來當(dāng)資料異動(dòng)的情境是修改時(shí)土榴,只更新有異動(dòng)的 Item,以增加程序運(yùn)作的效率响牛。

接下來的工作就是把 Adapter 整合到 MainActivity 的源代碼中:

public class MainActivity extends AppCompatActivity {

    private UserAdapter mUserAdapter;
    private TodoAdapter mTodoAdapter;

    @Override
    protected void onCreate(final Bundle inSavedInstanceState) {
        super.onCreate(inSavedInstanceState);
        super.setContentView(R.layout.activity_main);
        this.setupRecyclerView();
        this.setupSpinner();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // ask to get the list of user
        FluxContext.getInstance().getActionCreator().sendRequestAsync(USER_LOAD, USER_LOAD);
    }

    @Override
    protected void onStop() {
        super.onStop();

        // release resources
        if (this.mUserAdapter != null) {
            this.mUserAdapter.dispose();
        }
        if (this.mTodoAdapter != null) {
            this.mTodoAdapter.dispose();
        }
    }

    private void setupSpinner() {
        final Spinner spinner = (Spinner)super.findViewById(R.id.spinner);

        if (spinner != null) {
            // configure spinner to show data
            this.mUserAdapter = new UserAdapter();
            spinner.setAdapter(this.mUserAdapter);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(final AdapterView<?> inParent, final View inView,
                                           final int inPosition, final long inId) {
                    // when user change the selection of spinner, change the list of recyclerView
                    FluxContext.getInstance()
                            .getActionCreator()
                            .sendRequestAsync(TODO_LOAD, TODO_LOAD + ":" + inPosition);
                }

                @Override
                public void onNothingSelected(final AdapterView<?> inParent) {
                    // Do nothing
                }
            });
        }
    }

    private void setupRecyclerView() {
        final RecyclerView recyclerView = (RecyclerView)super.findViewById(R.id.recyclerView);

        if (recyclerView != null) {
            // configure recyclerView to show data
            this.mTodoAdapter = new TodoAdapter();
            recyclerView.setAdapter(this.mTodoAdapter);
        }
    }

}

除了把 Adapter 傳入對(duì)應(yīng)的畫面控件外玷禽,還有幾個(gè)重點(diǎn)。第一個(gè)是在 onStop 時(shí)要調(diào)用 Adapter 的 dispose 以避免之前提到的 Memory Leak 的問題呀打。另外一個(gè)是在 onStart 時(shí)會(huì)以非同步的方式要求提供 User 的清單數(shù)據(jù)矢赁,在畫面持續(xù)在前景運(yùn)作的同時(shí),UserStore 完成數(shù)據(jù)載入就會(huì)觸發(fā) UserAdapter贬丛、UserAdapter 再觸發(fā) Spinner撩银、Spinner 觸發(fā) TodoStore 的載入、TodoStore 觸發(fā) TodoAdapter豺憔、TodoAdapter 觸發(fā) RecyclerView 等一連串?dāng)?shù)據(jù)更新的動(dòng)作额获。所以可以在 Spinner 的 OnItemSelectedListener 中看到要求送出 TODO_LOAD 的 Action。

會(huì)選在 onStart 都做一次數(shù)據(jù)載入的要求是考量到 Activity 被推入背景后恭应,有可能會(huì)出現(xiàn)數(shù)據(jù)的異動(dòng)抄邀,所以強(qiáng)制進(jìn)行一次畫面的刷新。

寫到這里除了運(yùn)行所有已完成的單元測試外昼榛,其實(shí)可以再回去運(yùn)行一次 UAT境肾,這時(shí)可以發(fā)現(xiàn)已經(jīng)開始有測試結(jié)果轉(zhuǎn)為通過了。

編寫 Integration Test

在繼續(xù)完成需求之前胆屿,先插入一個(gè)有關(guān)測試上的說明奥喻,使用 Flux 的其中一個(gè)重要原因就是希望提高源代碼的可測試性。所以在這次的演示之中非迹,選擇以 Integration Test 來展示 FluxJava 可以達(dá)到的效果环鲤。

就像一開始提到的,用 Robolectric 來測試 MainActivity 被定位成 Integration Test憎兽。主要的測試目標(biāo)是要確認(rèn)整合起來后 UI 的行為符合設(shè)計(jì)的內(nèi)容冷离,此時(shí)當(dāng)然不希望使用真實(shí)的數(shù)據(jù)來測試结闸,簡單的說就是要把 Store 給隔離開來。

要達(dá)到這個(gè)目的可以由 FluxContext 的初始化做為切入點(diǎn)酒朵,以 Robolectric 來說桦锄,他提供了一個(gè)方便的功能,就是可以在測試運(yùn)行時(shí)以 Annotation 中設(shè)定的 Applicaton Class 取代原本的 Class蔫耽。 就如同以下源代碼所示范:

@Config(constants = BuildConfig, sdk = 21, application = StubAppConfig)
class MainActivitySpec extends GradleRoboSpecification {

}

而在 StubAppConfig 中就可以對(duì) FluxContext 注入測試用的 Class 來轉(zhuǎn)為提供測試用的數(shù)據(jù):

public class StubAppConfig extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        this.setupFlux();
    }

    private void setupFlux() {
        HashMap<Object, Class<?>> storeMap = new HashMap<>();

        storeMap.put(DATA_USER, StubUserStore.class);
        storeMap.put(DATA_TODO, StubTodoStore.class);

        FluxContext.getBuilder()
                .setBus(new Bus())
                .setActionHelper(new StubActionHelper())
                .setStoreMap(storeMap)
                .build();
    }

}

這里使用 StubAppConfig 做為切入點(diǎn)的演示并不是唯一的方法结耀,在實(shí)際應(yīng)用上還是應(yīng)該選擇適合自己項(xiàng)目的方式。

如果在運(yùn)行 UAT 希望也使用測試的數(shù)據(jù)來進(jìn)行匙铡,以 FluxJava 來說當(dāng)然也不會(huì)是問題图甜,達(dá)成的方式在本次的示范中也可以看得到。原理同樣是和 Integration Test 相同鳖眼,是使用取代原本 AppConfig 的方式黑毅。只是在 Espresso 里設(shè)定就會(huì)麻煩一點(diǎn),首先要增加一個(gè)自定義的 JUnitRunner钦讳,接著 build.gradledefaultConfig 改成以下的內(nèi)容:

defaultConfig {
    ...

    // replace "android.support.test.runner.AndroidJUnitRunner" with custom one
    testInstrumentationRunner "com.example.fluxjava.rx2.CustomJUnitRunner"

}

所以在運(yùn)行 UAT 與正常啟動(dòng)的情況下矿瘦,可以在畫面中看到截然不同的數(shù)據(jù)內(nèi)容,即代表 Store 代換的工作確實(shí)地達(dá)成目標(biāo)愿卒。


Production

Test

編寫新增 Todo 功能

在這次的演示中缚去,達(dá)成新增 Todo 的功能就只是很簡單地在 MainActivity 加上 Add Menu,透過用戶按下 Add 后琼开,顯示一個(gè) AlertDialog 取回用戶新增的內(nèi)容完成新增的程序易结。以下是 `menu_main.xml’ 的內(nèi)容:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/add"
        android:title="@string/add"
        app:showAsAction="always" />

</menu>

接著在 MainActivity.java 中加上以下的 Method:

@Override
public boolean onCreateOptionsMenu(final Menu inMenu) {
    super.getMenuInflater().inflate(R.menu.menu_main, inMenu);

    return true;
}

用來讓用戶輸入數(shù)據(jù)的 AlertDialog 是用 DialogFragment 來達(dá)成,以下是 Layout 的內(nèi)容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/title" />

        <EditText
            android:id="@+id/title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:inputType="text" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/memo" />

        <EditText
            android:id="@+id/memo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:inputType="text" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/due_date" />

        <EditText
            android:id="@+id/dueText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:inputType="text" />

    </LinearLayout>

</LinearLayout>

源代碼則是如下所示:

public class AddDialogFragment extends AppCompatDialogFragment {

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inInflater,
                             @Nullable final ViewGroup inContainer,
                             @Nullable final Bundle inSavedInstanceState) {
        return inInflater.inflate(R.layout.dialog_add, inContainer);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(final Bundle inSavedInstanceState) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(super.getActivity());
        final LayoutInflater inflater = super.getActivity().getLayoutInflater();
        final ViewGroup nullParent = null;

        // display an alertDialog for input a new todo item
        builder.setView(inflater.inflate(R.layout.dialog_add, nullParent))
                .setTitle(R.string.dialog_title)
                .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface inDialog, final int inId) {
                        final AlertDialog alertDialog = (AlertDialog)inDialog;
                        final Todo todo = new Todo();
                        final EditText title = (EditText)alertDialog.findViewById(R.id.title);
                        final EditText memo = (EditText)alertDialog.findViewById(R.id.memo);
                        final EditText dueDate = (EditText)alertDialog.findViewById(R.id.dueText);

                        if (title != null) {
                            todo.title = title.getText().toString();
                        }
                        if (memo != null) {
                            todo.memo = memo.getText().toString();
                        }
                        if (dueDate != null) {
                            todo.dueDate = dueDate.getText().toString();
                        }
                        // the input data will be sent to store by using bus
                        FluxContext.getInstance()
                                .getActionCreator()
                                .sendRequestAsync(TODO_ADD, todo);
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface inDialog, final int inId) {
                        // Do nothing
                    }
                });

        return builder.create();
    }

}

再來就是讓 MainActivity 可以在用戶按下 Menu 時(shí)彈出 AlertDialog柜候,所以新增如下的 Method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result;

    switch (item.getItemId()) {
        case R.id.add:
            AddDialogFragment addDialog = new AddDialogFragment();

            // display an input dialog to get a new todo
            addDialog.show(super.getSupportFragmentManager(), "Add");
            result = true;
            break;
        default:
            result = super.onOptionsItemSelected(item);
            break;
    }

    return result;
}

運(yùn)行所有的測試搞动,看測試的結(jié)果沒有通過的不多了,距完成只剩一步之遙渣刷。

編寫關(guān)閉 Todo 的功能

從最后一次 UAT 運(yùn)行的結(jié)果可以發(fā)現(xiàn)鹦肿,仍未滿足需求的項(xiàng)目只剩下關(guān)閉 Todo 最后一項(xiàng)。要達(dá)成這一項(xiàng)功能要回到 TodoAdapter飞主,將 onBindViewHolder 改成以下的內(nèi)容:

    @Override
    public void onBindViewHolder(final ViewHolder inViewHolder, final int inPosition) {
        final Todo item = this.mStore.getItem(inPosition);

        // bind data into item view of RecyclerView
        inViewHolder.title.setText(item.title);
        if (item.closed) {
            inViewHolder.title.setPaintFlags(
                    inViewHolder.title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            inViewHolder.title.setPaintFlags(
                    inViewHolder.title.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
        }
        inViewHolder.dueDate.setText(item.dueDate);
        inViewHolder.memo.setText(item.memo);
        inViewHolder.closed.setOnCheckedChangeListener(null);
        inViewHolder.closed.setChecked(item.closed);
        inViewHolder.closed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(final CompoundButton inButtonView, final boolean inIsChecked) {
                item.closed = inIsChecked;
                FluxContext.getInstance()
                        .getActionCreator()
                        .sendRequestAsync(TODO_CLOSE, item);
            }
        });
    }

最后狮惜,運(yùn)行最開始寫好的 UAT高诺,非常好碌识,所有的需求都通過測試,打完收工虱而!

更多深入的文章請(qǐng)參閱簡書 http://www.reibang.com/u/fea63707e07fwznote.blogspot.com

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末筏餐,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子牡拇,更是在濱河造成了極大的恐慌魁瞪,老刑警劉巖穆律,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異导俘,居然都是意外死亡峦耘,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門旅薄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來辅髓,“玉大人,你說我怎么就攤上這事少梁÷蹇冢” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵凯沪,是天一觀的道長第焰。 經(jīng)常有香客問我,道長妨马,這世上最難降的妖魔是什么挺举? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮烘跺,結(jié)果婚禮上豹悬,老公的妹妹穿的比我還像新娘。我一直安慰自己液荸,他們只是感情好瞻佛,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著娇钱,像睡著了一般伤柄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上文搂,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天适刀,我揣著相機(jī)與錄音,去河邊找鬼煤蹭。 笑死笔喉,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的硝皂。 我是一名探鬼主播常挚,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼稽物!你這毒婦竟也來了奄毡?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤贝或,失蹤者是張志新(化名)和其女友劉穎吼过,沒想到半個(gè)月后锐秦,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡盗忱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年酱床,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片趟佃。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡斤葱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出揖闸,到底是詐尸還是另有隱情揍堕,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布汤纸,位于F島的核電站衩茸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏贮泞。R本人自食惡果不足惜楞慈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望啃擦。 院中可真熱鬧囊蓝,春花似錦、人聲如沸令蛉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽珠叔。三九已至蝎宇,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間祷安,已是汗流浹背姥芥。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留汇鞭,地道東北人凉唐。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像霍骄,于是被迫代替她去往敵國和親台囱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

推薦閱讀更多精彩內(nèi)容

  • 想要追上最新的編程潮流嗎腕巡?想要導(dǎo)入最新的 Flux 編程方法嗎玄坦?這篇文章將手把手的帶你無痛進(jìn)入 Flux 與 Rx...
    _WZ_閱讀 2,426評(píng)論 0 9
  • 想要追上最新的編程潮流嗎?想要導(dǎo)入最新的 Flux 編程方法嗎绘沉?這篇文章將手把手的帶你無痛進(jìn)入 Flux 的領(lǐng)域煎楣。...
    _WZ_閱讀 4,430評(píng)論 0 3
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)车伞,斷路器择懂,智...
    卡卡羅2017閱讀 134,711評(píng)論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,305評(píng)論 25 707
  • 你能想象嗎谦去?有一天慷丽,你點(diǎn)的外賣由順豐小哥送上門,他臨走前還說了一句:“祝您用餐愉快鳄哭,麻煩給五星好評(píng)要糊,謝謝∽鼻穑”很出戲...
    惻隱之心_6bfd閱讀 397評(píng)論 0 0