App開發(fā)架構(gòu)指南(谷歌官方文檔譯文)(轉(zhuǎn))

文章轉(zhuǎn)自http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0523/7963.html

app開發(fā)者面臨的常見問題

跟傳統(tǒng)的桌面應(yīng)用開發(fā)不同,Android app的架構(gòu)要復(fù)雜得多踏施。一個典型的Android app是由多個app組件構(gòu)成的,包括activity,Fragment,service,content provider以及broadcast receiver奠货。而傳統(tǒng)的桌面應(yīng)用往往在一個龐大的單一的進(jìn)程中就完成了眨攘。

大多數(shù)的app組件都聲明在app manifest中垢揩,Android OS用它來決定如何將你的app與設(shè)備整合形成統(tǒng)一的用戶體驗。雖然就如剛說的亏推,桌面app只運行一個進(jìn)程学赛,但是一個優(yōu)秀的Android app卻需要更加靈活,因為用戶操作在不同app之間吞杭,不斷的切換流程和任務(wù)盏浇。

比如,當(dāng)你要在自己最喜歡的社交網(wǎng)絡(luò)app中分享一張照片的時候芽狗,你可以想象一下會發(fā)生什么绢掰。app觸發(fā)一個camera intent,然后Android OS啟動一個camera app來處理這一動作童擎。此時用戶已經(jīng)離開了社交網(wǎng)絡(luò)的app滴劲,但是用戶的操作體驗卻是無縫對接的。而 camera app反過來也可能觸發(fā)另一個intent顾复,比如啟動一個文件選擇器班挖,這可能會再次打開另一個app。最后用戶回到社交網(wǎng)絡(luò)app并分享照片芯砸。在這期間的任意時刻用戶都可被電話打斷萧芙,打完電話之后繼續(xù)回來分享照片。

在Android中假丧,這種app并行操作的行為是很常見的双揪,因此你的app必須正確處理這些流程。還要記住移動設(shè)備的資源是有限的包帚,因此任何時候操作系統(tǒng)都有可能殺死某些app渔期,為新運行的app騰出空間。

總的來說就是渴邦,你的app組件可能是單獨啟動并且是無序的疯趟,而且在任何時候都有可能被系統(tǒng)或者用戶銷毀。因為app組件生命的短暫性以及生命周期的不可控制性几莽,任何數(shù)據(jù)都不應(yīng)該把存放在app組件中迅办,同時app組件之間也不應(yīng)該相互依賴。

通用的架構(gòu)準(zhǔn)則

如果app組件不能存放數(shù)據(jù)和狀態(tài)章蚣,那么app還是可架構(gòu)的嗎?

最重要的一個原則就是盡量在app中做到separation of concerns(關(guān)注點分離)。常見的錯誤就是把所有代碼都寫在Activity或者Fragment中纤垂。任何跟UI和系統(tǒng)交互無關(guān)的事情都不應(yīng)該放在這些類當(dāng)中矾策。盡可能讓它們保持簡單輕量可以避免很多生命周期方面的問題。別忘了能并不擁有這些類峭沦,它們只是連接app和操作系統(tǒng)的橋梁贾虽。根據(jù)用戶的操作和其它因素,比如低內(nèi)存吼鱼,Android OS可能在任何時候銷毀它們蓬豁。為了提供可靠的用戶體驗,最好把對它們的依賴最小化菇肃。

第二個很重要的準(zhǔn)則是用model驅(qū)動UI地粪,最好是持久化的model。之所以要持久化是基于兩個原因:如果OS銷毀app釋放資源琐谤,用戶數(shù)據(jù)不會丟失蟆技;當(dāng)網(wǎng)絡(luò)很差或者斷網(wǎng)的時候app可以繼續(xù)工作。Model是負(fù)責(zé)app數(shù)據(jù)處理的組件斗忌。它們不依賴于View或者app 組件(Activity质礼,F(xiàn)ragment等),因此它們不會受那些組件的生命周期的影響织阳。保持UI代碼的簡單眶蕉,于業(yè)務(wù)邏輯分離可以讓它更易管理。

app架構(gòu)推薦

在這一小節(jié)中唧躲,我們將通過一個用例演示如何使用Architecture Component構(gòu)建一個app造挽。

注:沒有一種適合所有場景的app編寫方式。也就是說惊窖,這里推薦的架構(gòu)適合作為大多數(shù)用戶案例的開端刽宪。但是如果你已經(jīng)有了一種好的架構(gòu),沒有必要再去修改界酒。

假設(shè)我們在創(chuàng)建一個顯示用戶簡介的UI圣拄。用戶信息取自我們自己的私有的后端REST API。

創(chuàng)建用戶界面

UI由UserProfileFragment.java以及相應(yīng)的布局文件user_profile_layout.xml組成毁欣。

要驅(qū)動UI庇谆,我們的data model需要持有兩個數(shù)據(jù)元素。

User ID: 用戶的身份識別凭疮。最好使用fragment argument來傳遞這個數(shù)據(jù)饭耳。如果OS殺死了你的進(jìn)程,這個數(shù)據(jù)可以被保存下來执解,所以app再次啟動的時候id仍是可用的寞肖。

User object: 一個持有用戶信息數(shù)據(jù)的POJO對象。

我們將創(chuàng)建一個繼承ViewModel類的UserProfileViewModel來保存這一信息。

一個ViewModel為特定的UI組件提供數(shù)據(jù)新蟆,比如fragment 或者 activity觅赊,并負(fù)責(zé)和數(shù)據(jù)處理的業(yè)務(wù)邏輯部分通信,比如調(diào)用其它組件加載數(shù)據(jù)或者轉(zhuǎn)發(fā)用戶的修改琼稻。ViewModel并不知道View的存在吮螺,也不會被configuration change影響。

現(xiàn)在我們有了三個文件帕翻。

user_profile.xml: 定義頁面的UI

UserProfileViewModel.java: 為UI準(zhǔn)備數(shù)據(jù)的類

UserProfileFragment.java: 顯示ViewModel中的數(shù)據(jù)與響應(yīng)用戶交互的控制器

下面我們開始實現(xiàn)(為簡單起見鸠补,省略了布局文件):

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public class UserProfileViewModel extends ViewModel {

  2. private String userId;

  3. private User user;

  4. public void init(String userId) {

  5. this.userId = userId;

  6. }

  7. public User getUser() {

  8. return user;

  9. }

  10. }

</pre>

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public class UserProfileFragment extends LifecycleFragment {

  2. private static final String UID_KEY = "uid";

  3. private UserProfileViewModel viewModel;

  4. @Override

  5. public void onActivityCreated(@Nullable Bundle savedInstanceState) {

  6. super.onActivityCreated(savedInstanceState);

  7. String userId = getArguments().getString(UID_KEY);

  8. viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);

  9. viewModel.init(userId);

  10. }

  11. @Override

  12. public View onCreateView(LayoutInflater inflater,

  13. @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

  14. return inflater.inflate(R.layout.user_profile, container, false);

  15. }

  16. }

</pre>

注:上面的例子中繼承的是LifecycleFragment而不是Fragment類。等Architecture Component中的lifecycles API穩(wěn)定之后嘀掸,Android Support Library中的Fragment類也將實現(xiàn)LifecycleOwner紫岩。

現(xiàn)在我們有了這些代碼模塊,如何連接它們呢横殴?畢竟當(dāng)ViewModel的user成員設(shè)置之后被因,我們還需要把它顯示到界面上。這就要用到LiveData了衫仑。

LiveData是一個可觀察的數(shù)據(jù)持有者梨与。 無需明確在它與app組件之間創(chuàng)建依賴就可以觀察LiveData對象的變化。LiveData還考慮了app組件(activities, fragments, services)的生命周期狀態(tài)文狱,做了防止對象泄漏的事情粥鞋。

注:如果你已經(jīng)在使用RxJava或者Agera這樣的庫,你可以繼續(xù)使用它們瞄崇,而不使用LiveData呻粹。但是使用它們的時候要確保正確的處理生命周期的問題,與之相關(guān)的LifecycleOwner stopped的時候數(shù)據(jù)流要停止苏研,LifecycleOwner destroyed的時候數(shù)據(jù)流也要銷毀等浊。你也可以使用android.arch.lifecycle:reactivestreams讓LiveData和其它的響應(yīng)式數(shù)據(jù)流庫一起使用(比如, RxJava2)。

現(xiàn)在我們把UserProfileViewModel中的User成員替換成LiveData摹蘑,這樣當(dāng)數(shù)據(jù)發(fā)生變化的時候fragment就會接到通知筹燕。LiveData的妙處在于它是有生命周期意識的,當(dāng)它不再被需要的時候會自動清理引用衅鹿。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public class UserProfileViewModel extends ViewModel {
  2. ...
  3. private User user;
  4. private LiveData<User> user;
  5. public LiveData<User> getUser() {
  6. return user;
  7. }
  8. }

</pre>

現(xiàn)在我們修改UserProfileFragment撒踪,讓它觀察數(shù)據(jù)并更新UI。

<pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Override
  2. public void onActivityCreated(@Nullable Bundle savedInstanceState) {
  3. super.onActivityCreated(savedInstanceState);
  4. viewModel.getUser().observe(this, user -> {
  5. // update UI
  6. });
  7. }

</pre>

每當(dāng)User數(shù)據(jù)更新的時候 onChanged 回調(diào)將被觸發(fā)大渤,然后刷新UI制妄。

如果你熟悉其它library的observable callback的用法,你會意識到我們不需要重寫fragment的onStop()方法停止對數(shù)據(jù)的觀察泵三。因為LiveData是有生命周期意識的耕捞,也就是說除非fragment處于活動狀態(tài)衔掸,否則callback不會觸發(fā)。LiveData還可以在fragmentonDestroy()的時候自動移除observer砸脊。

對我們也沒有做任何特殊的操作來處理 configuration changes(比如旋轉(zhuǎn)屏幕)具篇。ViewModel可以在configuration change的時候自動保存下來纬霞,一旦新的fragment進(jìn)入生命周期凌埂,它將收到相同的ViewModel實例,并且攜帶當(dāng)前數(shù)據(jù)的callback將立即被調(diào)用诗芜。這就是為什么ViewModel不應(yīng)該直接引用任何View瞳抓,它們游離在View的生命周期之外。參見ViewModel的生命周期伏恐。

獲取數(shù)據(jù)

現(xiàn)在我們把ViewModel和fragment聯(lián)系了起來孩哑,但是ViewModel該如何獲取數(shù)據(jù)呢?在我們的例子中翠桦,假設(shè)后端提供一個REST API横蜒,我們使用Retrofit從后端提取數(shù)據(jù)。你也可以使用任何其它的library來達(dá)到相同的目的销凑。

下面是和后端交互的retrofit Webservice:

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public interface Webservice {
  2. /**
    • @GET declares an HTTP GET request
    • @Path("user") annotation on the userId parameter marks it as a
    • replacement for the {user} placeholder in the @GET path
  3. */
  4. @GET("/users/{user}")
  5. Call<User> getUser(@Path("user") String userId);
  6. }

</pre>

ViewModel的一個簡單的實現(xiàn)方式是直接調(diào)用Webservice獲取數(shù)據(jù)丛晌,然后把它賦值給User對象。雖然這樣可行斗幼,但是隨著app的增大會變得難以維護(hù)澎蛛。ViewModel的職責(zé)過多也違背了前面提到的關(guān)注點分離(separation of concerns)原則。另外蜕窿,ViewModel的有效時間是和ActivityFragment的生命周期綁定的谋逻,因此當(dāng)它的生命周期結(jié)束便丟失所有數(shù)據(jù)是一種不好的用戶體驗。相反桐经,我們的ViewModel將把這個工作代理給Repository模塊毁兆。

Repository模塊負(fù)責(zé)處理數(shù)據(jù)方面的操作。它們?yōu)閍pp提供一個簡潔的API阴挣。它們知道從哪里得到數(shù)據(jù)以及數(shù)據(jù)更新的時候調(diào)用什么API悯嗓。你可以把它們看成是不同數(shù)據(jù)源(persistent model, web service, cache, 等等)之間的媒介。

下面的UserRepository類使用了WebService來獲取用戶數(shù)據(jù)樟插。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public class UserRepository {
  2. private Webservice webservice;
  3. // ...
  4. public LiveData<User> getUser(int userId) {
  5. // This is not an optimal implementation, we'll fix it below
  6. final MutableLiveData<User> data = new MutableLiveData<>();
  7. webservice.getUser(userId).enqueue(new Callback<User>() {
  8. @Override
  9. public void onResponse(Call<User> call, Response<User> response) {
  10. // error case is left out for brevity
  11. data.setValue(response.body());
  12. }
  13. });
  14. return data;
  15. }
  16. }

</pre>

雖然repository模塊看起來沒什么必要怔鳖,但它其實演扮演著重要的角色;它把數(shù)據(jù)源從app中抽象出來『行叮現(xiàn)在我們的ViewModel并不知道數(shù)據(jù)是由Webservice提供的骗爆,意味著有必要的話可以替換成其它的實現(xiàn)方式。

注:為簡單起見我們省略了網(wǎng)絡(luò)錯誤出現(xiàn)的情況蔽介。實現(xiàn)了暴露網(wǎng)絡(luò)錯誤和加載狀態(tài)的版本見下面的Addendum: exposing network status摘投。

管理不同組件間的依賴:

前面的UserRepository類需要Webservice的實例才能完成它的工作煮寡。可以直接創(chuàng)建它就是了犀呼,但是為此我們還需要知道Webservice所依賴的東西才能構(gòu)建它幸撕。這顯著的增減了代碼的復(fù)雜度和偶合度(比如,每個需要Webservice實例的類都需要知道如何用它的依賴去構(gòu)建它)外臂。另外坐儿,UserRepository很可能不是唯一需要Webservice的類。如果每個類都創(chuàng)建一個新的WebService宋光,就變得很重了貌矿。

有兩種模式可以解決這個問題:

依賴注入: 依賴注入允許類在無需構(gòu)造依賴的情況下定義自己的依賴對象。在運行時由另一個類來負(fù)責(zé)提供這些依賴罪佳。在Android app中我們推薦使用谷歌的Dagger 2來實現(xiàn)依賴注入逛漫。Dagger 2 通過遍歷依賴樹自動構(gòu)建對象,并提供編譯時的依賴赘艳。

Service Locator:Service Locator 提供一個registry酌毡,類可以從這里得到它們的依賴而不是構(gòu)建它們。相對依賴注入來說要簡單些蕾管,所以如果你對依賴注入不熟悉枷踏,可以使用 Service Locator 。

這些模式允許你擴(kuò)展自己的代碼娇掏,因為它們提供了清晰的模式來管理依賴呕寝,而不是不斷的重復(fù)代碼。兩者均支持替換成mock依賴來測試婴梧,這也是使用它們主要優(yōu)勢之一下梢。

在這個例子中,我們將使用 Dagger 2 來管理依賴塞蹭。

連接ViewModel和repository

現(xiàn)在我們修改UserProfileViewModel以使用repository孽江。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public class UserProfileViewModel extends ViewModel {

  2. private LiveData<User> user;

  3. private UserRepository userRepo;

  4. @Inject // UserRepository parameter is provided by Dagger 2

  5. public UserProfileViewModel(UserRepository userRepo) {

  6. this.userRepo = userRepo;

  7. }

  8. public void init(String userId) {

  9. if (this.user != null) {

  10. // ViewModel is created per Fragment so

  11. // we know the userId won't change

  12. return;

  13. }

  14. user = userRepo.getUser(userId);

  15. }

  16. public LiveData<User> getUser() {

  17. return this.user;

  18. }

  19. }

</pre>

緩存數(shù)據(jù)

上面的repository對抽象web service調(diào)用是很好的,但是因為它只依賴于一個數(shù)據(jù)源番电,并不是非常實用岗屏。

UserRepository的問題在于當(dāng)獲取完數(shù)據(jù)之后,它并沒有把數(shù)據(jù)保存下來漱办。如果用戶離開UserProfileFragment然后在回來这刷,app會重新獲取數(shù)據(jù)。這是很不好的娩井,原因有二:1.浪費了帶寬資源暇屋,2.用戶被迫等待新的查詢完成。為了解決這個問題洞辣,我們向UserRepository中添加了一個新的數(shù)據(jù)源咐刨,它將把User對象緩存到內(nèi)存中昙衅。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Singleton // informs Dagger that this class should be constructed once

  2. public class UserRepository {

  3. private Webservice webservice;

  4. // simple in memory cache, details omitted for brevity

  5. private UserCache userCache;

  6. public LiveData<User> getUser(String userId) {

  7. LiveData<User> cached = userCache.get(userId);

  8. if (cached != null) {

  9. return cached;

  10. }

  11. final MutableLiveData<User> data = new MutableLiveData<>();

  12. userCache.put(userId, data);

  13. // this is still suboptimal but better than before.

  14. // a complete implementation must also handle the error cases.

  15. webservice.getUser(userId).enqueue(new Callback<User>() {

  16. @Override

  17. public void onResponse(Call<User> call, Response<User> response) {

  18. data.setValue(response.body());

  19. }

  20. });

  21. return data;

  22. }

  23. }

</pre>

持久化數(shù)據(jù)

目前的實現(xiàn)中,如果用戶旋轉(zhuǎn)屏幕或者是離開之后再次回到app定鸟,UI將立即可見而涉,因為repository是從常駐內(nèi)存的緩存中獲取的數(shù)據(jù)。但是如果用戶離開了app联予,幾個小時之后再回來時進(jìn)程已經(jīng)被殺死了怎么辦呢啼县?

以目前的實現(xiàn)來看,我們需要再次從網(wǎng)絡(luò)獲取數(shù)據(jù)躯泰。這不僅僅是糟糕的用戶體驗谭羔,還是一種浪費,因為它需要花費移動流量獲取相同的數(shù)據(jù)麦向。你可以直接緩存web請求,但是這又產(chǎn)生了新的問題客叉。如果同樣的user數(shù)據(jù)來自于另一個類型的請求呢(比如獲取一個朋友的列表)诵竭?那樣的話你的app很可能會顯示不一致的數(shù)據(jù),這是一種困惑的用戶體驗兼搏。例如卵慰,因為朋友列表請求與用戶請求可能在不同的時間執(zhí)行,同一用戶的數(shù)據(jù)可能會不一致佛呻。你的app需要融合它們以避免數(shù)據(jù)出現(xiàn)不一致裳朋。

處理這個問題的正確方式是使用持久化的model。持久化庫Room就是為此而生吓著。

Room是一個對象關(guān)系映射庫鲤嫡,以最少的代碼提供本地數(shù)據(jù)持久化功能。它在編譯時驗證每個查詢绑莺,所以損壞的SQL查詢只會導(dǎo)致編譯時錯誤而不是運行時崩潰暖眼。Room抽象了部分SQL查詢與表的相關(guān)操作的底層細(xì)節(jié)。它還可以讓你通過一個LiveData對象監(jiān)聽到數(shù)據(jù)庫數(shù)據(jù)的變化纺裁。另外诫肠,它還明確定義了線程約束,解決了諸如從主線程獲取存儲這樣的常見的問題欺缘。

注:如果熟悉其它的持久化方案比如SQLite ORM或者是一個不同的數(shù)據(jù)庫栋豫,如Realm,你不需要把它替換成Room谚殊,除非Room的特性對你的用例而言更加重要丧鸯。

要使用Room,我們需要定義本地的schema络凿。首先使用@Entity注解User類骡送,將它標(biāo)記為數(shù)據(jù)庫中的一張表昂羡。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Entity
  2. class User {
  3. @PrimaryKey
  4. private int id;
  5. private String name;
  6. private String lastName;
  7. // getters and setters for fields
  8. }

</pre>

然后通過繼承RoomDatabase創(chuàng)建一個database類:

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Database(entities = {User.class}, version = 1)
  2. public abstract class MyDatabase extends RoomDatabase {
  3. }

</pre>

注意MyDatabase是抽象類。Room根據(jù)它自動提供一個實現(xiàn)摔踱。詳細(xì)情況參見Room文檔虐先。

現(xiàn)在我們需要一個向數(shù)據(jù)庫插入數(shù)據(jù)的方法。為此創(chuàng)建一個data access object (DAO)派敷。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Dao
  2. public interface UserDao {
  3. @Insert(onConflict = REPLACE)
  4. void save(User user);
  5. @Query("SELECT * FROM user WHERE id = :userId")
  6. LiveData<User> load(String userId);
  7. }

</pre>

然后蛹批,在database類中引用DAO。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Database(entities = {User.class}, version = 1)
  2. public abstract class MyDatabase extends RoomDatabase {
  3. public abstract UserDao userDao();
  4. }

</pre>

注意load方法返回的是LiveData篮愉。Room知道database什么時候被修改過腐芍,當(dāng)數(shù)據(jù)變化的時候,它將自動通知所有處于活動狀態(tài)的observer试躏。

注:對于alpha 1 版本猪勇,Room是根據(jù)表的修改檢查驗證,因此可能會發(fā)送錯誤的信號颠蕴。

現(xiàn)在我們可以修改UserRepository以和Room協(xié)同工作泣刹。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. @Singleton

  2. public class UserRepository {

  3. private final Webservice webservice;

  4. private final UserDao userDao;

  5. private final Executor executor;

  6. @Inject

  7. public UserRepository(Webservice webservice, UserDao userDao, Executor executor) {

  8. this.webservice = webservice;

  9. this.userDao = userDao;

  10. this.executor = executor;

  11. }

  12. public LiveData<User> getUser(String userId) {

  13. refreshUser(userId);

  14. // return a LiveData directly from the database.

  15. return userDao.load(userId);

  16. }

  17. private void refreshUser(final String userId) {

  18. executor.execute(() -> {

  19. // running in a background thread

  20. // check if user was fetched recently

  21. boolean userExists = userDao.hasUser(FRESH_TIMEOUT);

  22. if (!userExists) {

  23. // refresh the data

  24. Response response = webservice.getUser(userId).execute();

  25. // TODO check for error etc.

  26. // Update the database.The LiveData will automatically refresh so

  27. // we don't need to do anything else here besides updating the database

  28. userDao.save(response.body());

  29. }

  30. });

  31. }

  32. }

</pre>

雖然我們在UserRepository中改變了數(shù)據(jù)來源,但是我們不需要修改UserProfileViewModel或者UserProfileFragment犀被。這就是抽象帶來的靈活性椅您。這對測試同樣有好處,因為你可以提供一個假的UserRepository來測試UserProfileViewModel寡键。

現(xiàn)在我們的代碼就完成了掀泳。如果用戶稍后回到相同的界面,將立即看到用戶信息西轩,因為這些信息做了持久化员舵。同時,如果數(shù)據(jù)過于陳舊遭商,repository將在后臺更新數(shù)據(jù)固灵。當(dāng)然,這取決于你的案例劫流,你可能會喜歡在數(shù)據(jù)太老的情況下不顯示持久化的數(shù)據(jù)巫玻。

在某些情況下,比如下拉刷新祠汇,在界面上顯示當(dāng)前是否正在進(jìn)行網(wǎng)絡(luò)操作是很重要的仍秤。把UI操作和和實際數(shù)據(jù)分離是一種很好的實踐,因為它可能因為各種原因而更新(比如可很,如果我們獲取一個朋友的列表诗力,同一用戶可能被再次獲取,從而觸發(fā)一個 LiveData<User> update)我抠。

這個問題有兩種常用的解決辦法:

  1. 把getUser修改成返回包含了網(wǎng)絡(luò)操作狀態(tài)的LiveData苇本。附: 暴露網(wǎng)絡(luò)狀態(tài)小節(jié)中提供了一個實現(xiàn)了的例子袜茧。

  2. 在repository類中另外提供一個可以返回User刷新狀態(tài)的公共的函數(shù)。如果只是為了明確的響應(yīng)用戶操作而在界面上顯示網(wǎng)絡(luò)狀態(tài)((比如 pull-to-refresh).)瓣窄,這種方式更好些笛厦。

單一數(shù)據(jù)源(Single source of truth)

不同的后端REST API返回相同的數(shù)據(jù)是很常見的事情。比如俺夕,如果有一個另外的后端地址返回一個朋友的列表裳凸,那么相同的User對象就有可能來自兩個不同的API地址,也許連內(nèi)容詳細(xì)程度都不一樣劝贸。如果UserRepository直接返回 Webservice 請求 的響應(yīng)姨谷,我們的UI就有可能顯示不一致,因為服務(wù)端的兩個請求之間數(shù)據(jù)是有區(qū)別的映九。這就是為什么在UserRepository的實現(xiàn)中梦湘,web service 的回調(diào)只是把數(shù)據(jù)保存在數(shù)據(jù)庫中。然后數(shù)據(jù)庫中的變化將觸發(fā)LiveData對象的callback氯迂。

在這個模型中践叠,database就是這里的單一數(shù)據(jù)源(Single source of truth),其它部分都是通過repository獲取它嚼蚀。不管你是否是使用磁盤緩存,我們都推薦你的repository指明一個可以作為single source of truth數(shù)據(jù)源供app其它部分使用管挟。

最終架構(gòu)

下面的圖標(biāo)顯示了我們所推薦的架構(gòu)的所有模塊以及它們之間是如何交互的:

final-architecture.png

指導(dǎo)原則

  • 編程是一種創(chuàng)造性的勞動轿曙,開發(fā)Android app也不例外。同一問題有許多種解決辦法僻孝,不管是activity或者fragment之間的數(shù)據(jù)交互导帝,還是獲取遠(yuǎn)程數(shù)據(jù)并緩存到本地,還是一個有一定規(guī)模的app可能遇到的其它常見問題穿铆。

  • 雖然下面的建議不是強(qiáng)制性的您单,但根據(jù)我們以往的經(jīng)驗,從長遠(yuǎn)來看荞雏,遵守它們可以讓你的代碼更加健壯虐秦,更加易于測試和維護(hù)。

  • manifest定義的入口-activity, service, broadcast receiver..等等凤优,都不是數(shù)據(jù)源悦陋,它們只應(yīng)該和與該入口相關(guān)的數(shù)據(jù)協(xié)作。因為每個app組件的生命都非常短暫筑辨,取決于用戶的行為以及設(shè)備運行時的狀況俺驶,你肯定不會希望把它們作為數(shù)據(jù)源。

  • app不同模塊之間要有明確的責(zé)任邊界棍辕。比如暮现,不要把加載網(wǎng)絡(luò)數(shù)據(jù)的代碼分散到不同的類或者包中还绘。同樣,也不要把不相關(guān)的職責(zé)-比如數(shù)據(jù)緩存和數(shù)據(jù)綁定-放在一個類中栖袋。

  • 每個模塊暴露的細(xì)節(jié)越少越好拍顷。不要圖一時爽快把模塊的內(nèi)部實現(xiàn)暴露出來。你可能當(dāng)時節(jié)省了一點時間栋荸,但隨著代碼的演變菇怀,你可能會付出不知翻了多少倍的技術(shù)債。

  • 在定義模塊之間的交互時晌块,思考如何做到各個模塊的獨立和可測試爱沟。比如,一個設(shè)計良好的網(wǎng)絡(luò)數(shù)據(jù)請求API可以讓緩存數(shù)據(jù)到本地數(shù)據(jù)庫模塊的測試更加簡單匆背。而如果把這兩個模塊的邏輯混到一起呼伸,或者把網(wǎng)絡(luò)請求的代碼分散到代碼的各處,都會使測試變得很難钝尸。

  • app的核心應(yīng)該可以讓app脫穎而出的那些東西括享,不要把時間花在重復(fù)造輪子和反復(fù)寫相同代碼的事情上。相反珍促,你應(yīng)該把自己的精力集中到如何使app獨一無二上铃辖。重復(fù)的工作就交給Android Architecture Components以及推薦的庫來處理吧。

  • 盡可能的持久化重要的猪叙,新生的數(shù)據(jù)娇斩,以便讓你的app在離線狀態(tài)下都可用。雖然你可能享受著高速的網(wǎng)絡(luò)穴翩,但你的用戶也許不是犬第。

  • repository應(yīng)該指派一個可以用作single source of truth的數(shù)據(jù)源。每當(dāng)app需要獲取一塊數(shù)據(jù)的時候芒帕,它總是來自這個single source of truth歉嗓。更多的信息參見上面的Single source of truth

附:暴露網(wǎng)絡(luò)狀態(tài)

在前面app架構(gòu)推薦一節(jié)中背蟆,為了保持例子的簡單鉴分,我們有意省略了網(wǎng)絡(luò)錯誤以及加載狀態(tài)。這一節(jié)我們將演示一種暴露網(wǎng)絡(luò)狀態(tài)的方法淆储,使用一個Resource類來封裝數(shù)據(jù)以及數(shù)據(jù)的狀態(tài)冠场。

下面是一個實現(xiàn)的例子:

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. //a generic class that describes a data with a status

  2. public class Resource<T> {

  3. @NonNull public final Status status;

  4. @Nullable public final T data;

  5. @Nullable public final String message;

  6. private Resource(@NonNull Status status, @Nullable T data, @Nullable String message) {

  7. this.status = status;

  8. this.data = data;

  9. this.message = message;

  10. }

  11. public static <T> Resource<T> success(@NonNull T data) {

  12. return new Resource<>(SUCCESS, data, null);

  13. }

  14. public static <T> Resource<T> error(String msg, @Nullable T data) {

  15. return new Resource<>(ERROR, data, msg);

  16. }

  17. public static <T> Resource<T> loading(@Nullable T data) {

  18. return new Resource<>(LOADING, data, null);

  19. }

  20. }

</pre>

因為從網(wǎng)絡(luò)加載數(shù)據(jù)而顯示從磁盤讀出的數(shù)據(jù)是一種常見的用例,我們將創(chuàng)建一個可以在多個地方重用的helper類:NetworkBoundResource本砰。

下面是NetworkBoundResource的決策樹:

network-bound-resource.png

首先從監(jiān)聽database獲取resource開始碴裙。當(dāng)?shù)谝淮螐臄?shù)據(jù)庫加載的時候,NetworkBoundResource檢查得到的結(jié)果是否可以分發(fā)或者需要從網(wǎng)絡(luò)獲取。注意這兩者可能同時發(fā)生舔株,因為當(dāng)從網(wǎng)絡(luò)更新緩存數(shù)據(jù)的時候往往還需要顯示數(shù)據(jù)莺琳。

如果網(wǎng)絡(luò)調(diào)用成功完成,將響應(yīng)結(jié)果保存到數(shù)據(jù)庫中载慈,然后重新初始化數(shù)據(jù)流惭等。如果請求失敗,我們直接發(fā)出一個錯誤信號办铡。

下面是NetworkBoundResource類為其子類提供的公共API:

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. // ResultType: Type for the Resource data

  2. // RequestType: Type for the API response

  3. public abstract class NetworkBoundResource<ResultType, RequestType> {

  4. // Called to save the result of the API response into the database

  5. @WorkerThread

  6. protected abstract void saveCallResult(@NonNull RequestType item);

  7. // Called with the data in the database to decide whether it should be

  8. // fetched from the network.

  9. @MainThread

  10. protected abstract boolean shouldFetch(@Nullable ResultType data);

  11. // Called to get the cached data from the database

  12. @NonNull @MainThread

  13. protected abstract LiveData<ResultType> loadFromDb();

  14. // Called to create the API call.

  15. @NonNull @MainThread

  16. protected abstract LiveData<ApiResponse<RequestType>> createCall();

  17. // Called when the fetch fails. The child class may want to reset components

  18. // like rate limiter.

  19. @MainThread

  20. protected void onFetchFailed() {

  21. }

  22. // returns a LiveData that represents the resource

  23. public final LiveData<Resource<ResultType>> getAsLiveData() {

  24. return result;

  25. }

  26. }

</pre>

注意上面的類定義了兩個類型的參數(shù)(ResultType,RequestType)辞做,因為API返回的數(shù)據(jù)類型可能和本地使用的數(shù)據(jù)類型不一致。

同時注意上面的代碼使用了 ApiResponse 作為網(wǎng)絡(luò)請求寡具, ApiResponse 是對Retrofit2.Call 類的簡單封裝秤茅,用于將其響應(yīng)轉(zhuǎn)換為LiveData。

下面是NetworkBoundResource類其余的實現(xiàn):

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. public abstract class NetworkBoundResource<ResultType, RequestType> {

  2. private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>();

  3. @MainThread

  4. NetworkBoundResource() {

  5. result.setValue(Resource.loading(null));

  6. LiveData<ResultType> dbSource = loadFromDb();

  7. result.addSource(dbSource, data -> {

  8. result.removeSource(dbSource);

  9. if (shouldFetch(data)) {

  10. fetchFromNetwork(dbSource);

  11. } else {

  12. result.addSource(dbSource,

  13. newData -> result.setValue(Resource.success(newData)));

  14. }

  15. });

  16. }

  17. private void fetchFromNetwork(final LiveData<ResultType> dbSource) {

  18. LiveData<ApiResponse<RequestType>> apiResponse = createCall();

  19. // we re-attach dbSource as a new source,

  20. // it will dispatch its latest value quickly

  21. result.addSource(dbSource,

  22. newData -> result.setValue(Resource.loading(newData)));

  23. result.addSource(apiResponse, response -> {

  24. result.removeSource(apiResponse);

  25. result.removeSource(dbSource);

  26. //noinspection ConstantConditions

  27. if (response.isSuccessful()) {

  28. saveResultAndReInit(response);

  29. } else {

  30. onFetchFailed();

  31. result.addSource(dbSource,

  32. newData -> result.setValue(

  33. Resource.error(response.errorMessage, newData)));

  34. }

  35. });

  36. }

  37. @MainThread

  38. private void saveResultAndReInit(ApiResponse<RequestType> response) {

  39. new AsyncTask<Void, Void, Void>() {

  40. @Override

  41. protected Void doInBackground(Void... voids) {

  42. saveCallResult(response.body);

  43. return null;

  44. }

  45. @Override

  46. protected void onPostExecute(Void aVoid) {

  47. // we specially request a new live data,

  48. // otherwise we will get immediately last cached value,

  49. // which may not be updated with latest results received from network.

  50. result.addSource(loadFromDb(),

  51. newData -> result.setValue(Resource.success(newData)));

  52. }

  53. }.execute();

  54. }

  55. }

</pre>

現(xiàn)在我們就可以在repository中使用NetworkBoundResource來寫實現(xiàn)用戶的磁盤和網(wǎng)絡(luò)操作了童叠。

<pre class="brush:js;toolbar:false prettyprint linenums prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; font-size: 14px; display: block; padding: 1.5em; margin: 0px 0px 20px; line-height: 1.42857; word-break: break-all; word-wrap: break-word; color: rgb(51, 51, 51); background: rgb(47, 54, 64); border: 0px !important; border-radius: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. class UserRepository {

  2. Webservice webservice;

  3. UserDao userDao;

  4. public LiveData<Resource<User>> loadUser(final String userId) {

  5. return new NetworkBoundResource<User,User>() {

  6. @Override

  7. protected void saveCallResult(@NonNull User item) {

  8. userDao.insert(item);

  9. }

  10. @Override

  11. protected boolean shouldFetch(@Nullable User data) {

  12. return rateLimiter.canFetch(userId) && (data == null || !isFresh(data));

  13. }

  14. @NonNull @Override

  15. protected LiveData<User> loadFromDb() {

  16. return userDao.load(userId);

  17. }

  18. @NonNull @Override

  19. protected LiveData<ApiResponse<User>> createCall() {

  20. return webservice.getUser(userId);

  21. }

  22. }.getAsLiveData();

  23. }

  24. }

</pre>

原文地址:https://developer.android.com/topic/libraries/architecture/guide.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末框喳,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子厦坛,更是在濱河造成了極大的恐慌五垮,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件杜秸,死亡現(xiàn)場離奇詭異放仗,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)撬碟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進(jìn)店門匙监,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人小作,你說我怎么就攤上這事〖诠常” “怎么了顾稀?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長坝撑。 經(jīng)常有香客問我静秆,道長,這世上最難降的妖魔是什么巡李? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任抚笔,我火速辦了婚禮,結(jié)果婚禮上侨拦,老公的妹妹穿的比我還像新娘殊橙。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布膨蛮。 她就那樣靜靜地躺著叠纹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪敞葛。 梳的紋絲不亂的頭發(fā)上誉察,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機(jī)與錄音惹谐,去河邊找鬼持偏。 笑死,一個胖子當(dāng)著我的面吹牛氨肌,可吹牛的內(nèi)容都是我干的鸿秆。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼儒飒,長吁一口氣:“原來是場噩夢啊……” “哼谬莹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起桩了,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤附帽,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后井誉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蕉扮,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年颗圣,在試婚紗的時候發(fā)現(xiàn)自己被綠了喳钟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡在岂,死狀恐怖奔则,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蔽午,我是刑警寧澤易茬,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站及老,受9級特大地震影響抽莱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜骄恶,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一食铐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧僧鲁,春花似錦虐呻、人聲如沸象泵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽单芜。三九已至,卻和暖如春犁柜,著一層夾襖步出監(jiān)牢的瞬間洲鸠,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工馋缅, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留扒腕,地道東北人。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓萤悴,卻偏偏與公主長得像瘾腰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子覆履,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,647評論 2 354

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