文章轉(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;">
public class UserProfileViewModel extends ViewModel {
private String userId;
private User user;
public void init(String userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
}
</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;">
public class UserProfileFragment extends LifecycleFragment {
private static final String UID_KEY = "uid";
private UserProfileViewModel viewModel;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String userId = getArguments().getString(UID_KEY);
viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
viewModel.init(userId);
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.user_profile, container, false);
}
}
</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;">
- public class UserProfileViewModel extends ViewModel {
- ...
- private User user;
- private LiveData<User> user;
- public LiveData<User> getUser() {
- return user;
- }
- }
</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;">
- @Override
- public void onActivityCreated(@Nullable Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- viewModel.getUser().observe(this, user -> {
- // update UI
- });
- }
</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;">
- public interface Webservice {
- /**
- @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
- */
- @GET("/users/{user}")
- Call<User> getUser(@Path("user") String userId);
- }
</pre>
ViewModel的一個簡單的實現(xiàn)方式是直接調(diào)用Webservice獲取數(shù)據(jù)丛晌,然后把它賦值給User對象。雖然這樣可行斗幼,但是隨著app的增大會變得難以維護(hù)澎蛛。ViewModel的職責(zé)過多也違背了前面提到的關(guān)注點分離(separation of concerns)原則。另外蜕窿,ViewModel的有效時間是和Activity和Fragment的生命周期綁定的谋逻,因此當(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;">
- public class UserRepository {
- private Webservice webservice;
- // ...
- public LiveData<User> getUser(int userId) {
- // This is not an optimal implementation, we'll fix it below
- final MutableLiveData<User> data = new MutableLiveData<>();
- webservice.getUser(userId).enqueue(new Callback<User>() {
- @Override
- public void onResponse(Call<User> call, Response<User> response) {
- // error case is left out for brevity
- data.setValue(response.body());
- }
- });
- return data;
- }
- }
</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;">
public class UserProfileViewModel extends ViewModel {
private LiveData<User> user;
private UserRepository userRepo;
@Inject // UserRepository parameter is provided by Dagger 2
public UserProfileViewModel(UserRepository userRepo) {
this.userRepo = userRepo;
}
public void init(String userId) {
if (this.user != null) {
// ViewModel is created per Fragment so
// we know the userId won't change
return;
}
user = userRepo.getUser(userId);
}
public LiveData<User> getUser() {
return this.user;
}
}
</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;">
@Singleton // informs Dagger that this class should be constructed once
public class UserRepository {
private Webservice webservice;
// simple in memory cache, details omitted for brevity
private UserCache userCache;
public LiveData<User> getUser(String userId) {
LiveData<User> cached = userCache.get(userId);
if (cached != null) {
return cached;
}
final MutableLiveData<User> data = new MutableLiveData<>();
userCache.put(userId, data);
// this is still suboptimal but better than before.
// a complete implementation must also handle the error cases.
webservice.getUser(userId).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
data.setValue(response.body());
}
});
return data;
}
}
</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;">
- @Entity
- class User {
- @PrimaryKey
- private int id;
- private String name;
- private String lastName;
- // getters and setters for fields
- }
</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;">
- @Database(entities = {User.class}, version = 1)
- public abstract class MyDatabase extends RoomDatabase {
- }
</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;">
- @Dao
- public interface UserDao {
- @Insert(onConflict = REPLACE)
- void save(User user);
- @Query("SELECT * FROM user WHERE id = :userId")
- LiveData<User> load(String userId);
- }
</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;">
- @Database(entities = {User.class}, version = 1)
- public abstract class MyDatabase extends RoomDatabase {
- public abstract UserDao userDao();
- }
</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;">
@Singleton
public class UserRepository {
private final Webservice webservice;
private final UserDao userDao;
private final Executor executor;
@Inject
public UserRepository(Webservice webservice, UserDao userDao, Executor executor) {
this.webservice = webservice;
this.userDao = userDao;
this.executor = executor;
}
public LiveData<User> getUser(String userId) {
refreshUser(userId);
// return a LiveData directly from the database.
return userDao.load(userId);
}
private void refreshUser(final String userId) {
executor.execute(() -> {
// running in a background thread
// check if user was fetched recently
boolean userExists = userDao.hasUser(FRESH_TIMEOUT);
if (!userExists) {
// refresh the data
Response response = webservice.getUser(userId).execute();
// TODO check for error etc.
// Update the database.The LiveData will automatically refresh so
// we don't need to do anything else here besides updating the database
userDao.save(response.body());
}
});
}
}
</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)我抠。
這個問題有兩種常用的解決辦法:
把getUser修改成返回包含了網(wǎng)絡(luò)操作狀態(tài)的LiveData苇本。附: 暴露網(wǎng)絡(luò)狀態(tài)小節(jié)中提供了一個實現(xiàn)了的例子袜茧。
在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)的所有模塊以及它們之間是如何交互的:
指導(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;">
//a generic class that describes a data with a status
public class Resource<T> {
@NonNull public final Status status;
@Nullable public final T data;
@Nullable public final String message;
private Resource(@NonNull Status status, @Nullable T data, @Nullable String message) {
this.status = status;
this.data = data;
this.message = message;
}
public static <T> Resource<T> success(@NonNull T data) {
return new Resource<>(SUCCESS, data, null);
}
public static <T> Resource<T> error(String msg, @Nullable T data) {
return new Resource<>(ERROR, data, msg);
}
public static <T> Resource<T> loading(@Nullable T data) {
return new Resource<>(LOADING, data, null);
}
}
</pre>
因為從網(wǎng)絡(luò)加載數(shù)據(jù)而顯示從磁盤讀出的數(shù)據(jù)是一種常見的用例,我們將創(chuàng)建一個可以在多個地方重用的helper類:NetworkBoundResource本砰。
下面是NetworkBoundResource的決策樹:
首先從監(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;">
// ResultType: Type for the Resource data
// RequestType: Type for the API response
public abstract class NetworkBoundResource<ResultType, RequestType> {
// Called to save the result of the API response into the database
@WorkerThread
protected abstract void saveCallResult(@NonNull RequestType item);
// Called with the data in the database to decide whether it should be
// fetched from the network.
@MainThread
protected abstract boolean shouldFetch(@Nullable ResultType data);
// Called to get the cached data from the database
@NonNull @MainThread
protected abstract LiveData<ResultType> loadFromDb();
// Called to create the API call.
@NonNull @MainThread
protected abstract LiveData<ApiResponse<RequestType>> createCall();
// Called when the fetch fails. The child class may want to reset components
// like rate limiter.
@MainThread
protected void onFetchFailed() {
}
// returns a LiveData that represents the resource
public final LiveData<Resource<ResultType>> getAsLiveData() {
return result;
}
}
</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;">
public abstract class NetworkBoundResource<ResultType, RequestType> {
private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>();
@MainThread
NetworkBoundResource() {
result.setValue(Resource.loading(null));
LiveData<ResultType> dbSource = loadFromDb();
result.addSource(dbSource, data -> {
result.removeSource(dbSource);
if (shouldFetch(data)) {
fetchFromNetwork(dbSource);
} else {
result.addSource(dbSource,
newData -> result.setValue(Resource.success(newData)));
}
});
}
private void fetchFromNetwork(final LiveData<ResultType> dbSource) {
LiveData<ApiResponse<RequestType>> apiResponse = createCall();
// we re-attach dbSource as a new source,
// it will dispatch its latest value quickly
result.addSource(dbSource,
newData -> result.setValue(Resource.loading(newData)));
result.addSource(apiResponse, response -> {
result.removeSource(apiResponse);
result.removeSource(dbSource);
//noinspection ConstantConditions
if (response.isSuccessful()) {
saveResultAndReInit(response);
} else {
onFetchFailed();
result.addSource(dbSource,
newData -> result.setValue(
Resource.error(response.errorMessage, newData)));
}
});
}
@MainThread
private void saveResultAndReInit(ApiResponse<RequestType> response) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
saveCallResult(response.body);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
// we specially request a new live data,
// otherwise we will get immediately last cached value,
// which may not be updated with latest results received from network.
result.addSource(loadFromDb(),
newData -> result.setValue(Resource.success(newData)));
}
}.execute();
}
}
</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;">
class UserRepository {
Webservice webservice;
UserDao userDao;
public LiveData<Resource<User>> loadUser(final String userId) {
return new NetworkBoundResource<User,User>() {
@Override
protected void saveCallResult(@NonNull User item) {
userDao.insert(item);
}
@Override
protected boolean shouldFetch(@Nullable User data) {
return rateLimiter.canFetch(userId) && (data == null || !isFresh(data));
}
@NonNull @Override
protected LiveData<User> loadFromDb() {
return userDao.load(userId);
}
@NonNull @Override
protected LiveData<ApiResponse<User>> createCall() {
return webservice.getUser(userId);
}
}.getAsLiveData();
}
}
</pre>
原文地址:https://developer.android.com/topic/libraries/architecture/guide.html