人人做人人干-人人做人人看-人人做人人爽国产视-人人做人人爽人人爱-色屋视频-色屋网

歡迎您光臨深圳塔燈網絡科技有限公司!
電話圖標 余先生:13699882642

網站百科

為您解碼網站建設的點點滴滴

App開發架構指南(谷歌官方文檔譯文)(轉)

發表日期:2018-08 文章編輯:小燈 瀏覽次數:3139

文章轉自http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0523/7963.html

app開發者面臨的常見問題

跟傳統的桌面應用開發不同,Android app的架構要復雜得多。一個典型的Android app是由多個app組件構成的,包括activity,Fragment,service,content provider以及broadcast receiver。而傳統的桌面應用往往在一個龐大的單一的進程中就完成了。

大多數的app組件都聲明在app manifest中,Android OS用它來決定如何將你的app與設備整合形成統一的用戶體驗。雖然就如剛說的,桌面app只運行一個進程,但是一個優秀的Android app卻需要更加靈活,因為用戶操作在不同app之間,不斷的切換流程和任務。

比如,當你要在自己最喜歡的社交網絡app中分享一張照片的時候,你可以想象一下會發生什么。app觸發一個camera intent,然后Android OS啟動一個camera app來處理這一動作。此時用戶已經離開了社交網絡的app,但是用戶的操作體驗卻是無縫對接的。而 camera app反過來也可能觸發另一個intent,比如啟動一個文件選擇器,這可能會再次打開另一個app。最后用戶回到社交網絡app并分享照片。在這期間的任意時刻用戶都可被電話打斷,打完電話之后繼續回來分享照片。

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

總的來說就是,你的app組件可能是單獨啟動并且是無序的,而且在任何時候都有可能被系統或者用戶銷毀。因為app組件生命的短暫性以及生命周期的不可控制性,任何數據都不應該把存放在app組件中,同時app組件之間也不應該相互依賴。

通用的架構準則

如果app組件不能存放數據和狀態,那么app還是可架構的嗎?

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

第二個很重要的準則是用model驅動UI,最好是持久化的model。之所以要持久化是基于兩個原因:如果OS銷毀app釋放資源,用戶數據不會丟失;當網絡很差或者斷網的時候app可以繼續工作。Model是負責app數據處理的組件。它們不依賴于View或者app 組件(Activity,Fragment等),因此它們不會受那些組件的生命周期的影響。保持UI代碼的簡單,于業務邏輯分離可以讓它更易管理。

app架構推薦

在這一小節中,我們將通過一個用例演示如何使用Architecture Component構建一個app。

注:沒有一種適合所有場景的app編寫方式。也就是說,這里推薦的架構適合作為大多數用戶案例的開端。但是如果你已經有了一種好的架構,沒有必要再去修改。

假設我們在創建一個顯示用戶簡介的UI。用戶信息取自我們自己的私有的后端REST API。

創建用戶界面

UI由UserProfileFragment.java以及相應的布局文件user_profile_layout.xml組成。

要驅動UI,我們的data model需要持有兩個數據元素。

User ID: 用戶的身份識別。最好使用fragment argument來傳遞這個數據。如果OS殺死了你的進程,這個數據可以被保存下來,所以app再次啟動的時候id仍是可用的。

User object: 一個持有用戶信息數據的POJO對象。

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

一個ViewModel為特定的UI組件提供數據,比如fragment 或者 activity,并負責和數據處理的業務邏輯部分通信,比如調用其它組件加載數據或者轉發用戶的修改。ViewModel并不知道View的存在,也不會被configuration change影響。

現在我們有了三個文件。

user_profile.xml: 定義頁面的UI

UserProfileViewModel.java: 為UI準備數據的類

UserProfileFragment.java: 顯示ViewModel中的數據與響應用戶交互的控制器

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

<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穩定之后,Android Support Library中的Fragment類也將實現LifecycleOwner。

現在我們有了這些代碼模塊,如何連接它們呢?畢竟當ViewModel的user成員設置之后,我們還需要把它顯示到界面上。這就要用到LiveData了。

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

注:如果你已經在使用RxJava或者Agera這樣的庫,你可以繼續使用它們,而不使用LiveData。但是使用它們的時候要確保正確的處理生命周期的問題,與之相關的LifecycleOwner stopped的時候數據流要停止,LifecycleOwnerdestroyed的時候數據流也要銷毀。你也可以使用android.arch.lifecycle:reactivestreams讓LiveData和其它的響應式數據流庫一起使用(比如, RxJava2)。

現在我們把UserProfileViewModel中的User成員替換成LiveData,這樣當數據發生變化的時候fragment就會接到通知。LiveData的妙處在于它是有生命周期意識的,當它不再被需要的時候會自動清理引用。

<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>

現在我們修改UserProfileFragment,讓它觀察數據并更新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>

每當User數據更新的時候 onChanged 回調將被觸發,然后刷新UI。

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

對我們也沒有做任何特殊的操作來處理 configuration changes(比如旋轉屏幕)。ViewModel可以在configuration change的時候自動保存下來,一旦新的fragment進入生命周期,它將收到相同的ViewModel實例,并且攜帶當前數據的callback將立即被調用。這就是為什么ViewModel不應該直接引用任何View,它們游離在View的生命周期之外。參見ViewModel的生命周期。

獲取數據

現在我們把ViewModel和fragment聯系了起來,但是ViewModel該如何獲取數據呢?在我們的例子中,假設后端提供一個REST API,我們使用Retrofit從后端提取數據。你也可以使用任何其它的library來達到相同的目的。

下面是和后端交互的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的一個簡單的實現方式是直接調用Webservice獲取數據,然后把它賦值給User對象。雖然這樣可行,但是隨著app的增大會變得難以維護。ViewModel的職責過多也違背了前面提到的關注點分離(separation of concerns)原則。另外,ViewModel的有效時間是和Activity和Fragment的生命周期綁定的,因此當它的生命周期結束便丟失所有數據是一種不好的用戶體驗。相反,我們的ViewModel將把這個工作代理給Repository模塊。

Repository模塊負責處理數據方面的操作。它們為app提供一個簡潔的API。它們知道從哪里得到數據以及數據更新的時候調用什么API。你可以把它們看成是不同數據源(persistent model, web service, cache, 等等)之間的媒介。

下面的UserRepository類使用了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 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模塊看起來沒什么必要,但它其實演扮演著重要的角色;它把數據源從app中抽象出來。現在我們的ViewModel并不知道數據是由Webservice提供的,意味著有必要的話可以替換成其它的實現方式。

注:為簡單起見我們省略了網絡錯誤出現的情況。實現了暴露網絡錯誤和加載狀態的版本見下面的Addendum: exposing network status。

管理不同組件間的依賴:

前面的UserRepository類需要Webservice的實例才能完成它的工作。可以直接創建它就是了,但是為此我們還需要知道Webservice所依賴的東西才能構建它。這顯著的增減了代碼的復雜度和偶合度(比如,每個需要Webservice實例的類都需要知道如何用它的依賴去構建它)。另外,UserRepository很可能不是唯一需要Webservice的類。如果每個類都創建一個新的WebService,就變得很重了。

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

依賴注入: 依賴注入允許類在無需構造依賴的情況下定義自己的依賴對象。在運行時由另一個類來負責提供這些依賴。在Android app中我們推薦使用谷歌的Dagger 2來實現依賴注入。Dagger 2 通過遍歷依賴樹自動構建對象,并提供編譯時的依賴。

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

這些模式允許你擴展自己的代碼,因為它們提供了清晰的模式來管理依賴,而不是不斷的重復代碼。兩者均支持替換成mock依賴來測試,這也是使用它們主要優勢之一。

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

連接ViewModel和repository

現在我們修改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>

緩存數據

上面的repository對抽象web service調用是很好的,但是因為它只依賴于一個數據源,并不是非常實用。

UserRepository的問題在于當獲取完數據之后,它并沒有把數據保存下來。如果用戶離開UserProfileFragment然后在回來,app會重新獲取數據。這是很不好的,原因有二:1.浪費了帶寬資源,2.用戶被迫等待新的查詢完成。為了解決這個問題,我們向UserRepository中添加了一個新的數據源,它將把User對象緩存到內存中。

<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>

持久化數據

目前的實現中,如果用戶旋轉屏幕或者是離開之后再次回到app,UI將立即可見,因為repository是從常駐內存的緩存中獲取的數據。但是如果用戶離開了app,幾個小時之后再回來時進程已經被殺死了怎么辦呢?

以目前的實現來看,我們需要再次從網絡獲取數據。這不僅僅是糟糕的用戶體驗,還是一種浪費,因為它需要花費移動流量獲取相同的數據。你可以直接緩存web請求,但是這又產生了新的問題。如果同樣的user數據來自于另一個類型的請求呢(比如獲取一個朋友的列表)?那樣的話你的app很可能會顯示不一致的數據,這是一種困惑的用戶體驗。例如,因為朋友列表請求與用戶請求可能在不同的時間執行,同一用戶的數據可能會不一致。你的app需要融合它們以避免數據出現不一致。

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

Room是一個對象關系映射庫,以最少的代碼提供本地數據持久化功能。它在編譯時驗證每個查詢,所以損壞的SQL查詢只會導致編譯時錯誤而不是運行時崩潰。Room抽象了部分SQL查詢與表的相關操作的底層細節。它還可以讓你通過一個LiveData對象監聽到數據庫數據的變化。另外,它還明確定義了線程約束,解決了諸如從主線程獲取存儲這樣的常見的問題。

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

要使用Room,我們需要定義本地的schema。首先使用@Entity注解User類,將它標記為數據庫中的一張表。

<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創建一個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根據它自動提供一個實現。詳細情況參見Room文檔。

現在我們需要一個向數據庫插入數據的方法。為此創建一個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什么時候被修改過,當數據變化的時候,它將自動通知所有處于活動狀態的observer。

注:對于alpha 1 版本,Room是根據表的修改檢查驗證,因此可能會發送錯誤的信號。

現在我們可以修改UserRepository以和Room協同工作。

<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中改變了數據來源,但是我們不需要修改UserProfileViewModel或者UserProfileFragment。這就是抽象帶來的靈活性。這對測試同樣有好處,因為你可以提供一個假的UserRepository來測試UserProfileViewModel。

現在我們的代碼就完成了。如果用戶稍后回到相同的界面,將立即看到用戶信息,因為這些信息做了持久化。同時,如果數據過于陳舊,repository將在后臺更新數據。當然,這取決于你的案例,你可能會喜歡在數據太老的情況下不顯示持久化的數據。

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

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

  1. 把getUser修改成返回包含了網絡操作狀態的LiveData。附: 暴露網絡狀態小節中提供了一個實現了的例子。

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

單一數據源(Single source of truth)

不同的后端REST API返回相同的數據是很常見的事情。比如,如果有一個另外的后端地址返回一個朋友的列表,那么相同的User對象就有可能來自兩個不同的API地址,也許連內容詳細程度都不一樣。如果UserRepository直接返回 Webservice 請求 的響應,我們的UI就有可能顯示不一致,因為服務端的兩個請求之間數據是有區別的。這就是為什么在UserRepository的實現中,web service 的回調只是把數據保存在數據庫中。然后數據庫中的變化將觸發LiveData對象的callback。

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

最終架構

下面的圖標顯示了我們所推薦的架構的所有模塊以及它們之間是如何交互的:

final-architecture.png

指導原則

  • 編程是一種創造性的勞動,開發Android app也不例外。同一問題有許多種解決辦法,不管是activity或者fragment之間的數據交互,還是獲取遠程數據并緩存到本地,還是一個有一定規模的app可能遇到的其它常見問題。

  • 雖然下面的建議不是強制性的,但根據我們以往的經驗,從長遠來看,遵守它們可以讓你的代碼更加健壯,更加易于測試和維護。

  • manifest定義的入口-activity, service, broadcast receiver..等等,都不是數據源,它們只應該和與該入口相關的數據協作。因為每個app組件的生命都非常短暫,取決于用戶的行為以及設備運行時的狀況,你肯定不會希望把它們作為數據源。

  • app不同模塊之間要有明確的責任邊界。比如,不要把加載網絡數據的代碼分散到不同的類或者包中。同樣,也不要把不相關的職責-比如數據緩存和數據綁定-放在一個類中。

  • 每個模塊暴露的細節越少越好。不要圖一時爽快把模塊的內部實現暴露出來。你可能當時節省了一點時間,但隨著代碼的演變,你可能會付出不知翻了多少倍的技術債。

  • 在定義模塊之間的交互時,思考如何做到各個模塊的獨立和可測試。比如,一個設計良好的網絡數據請求API可以讓緩存數據到本地數據庫模塊的測試更加簡單。而如果把這兩個模塊的邏輯混到一起,或者把網絡請求的代碼分散到代碼的各處,都會使測試變得很難。

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

  • 盡可能的持久化重要的,新生的數據,以便讓你的app在離線狀態下都可用。雖然你可能享受著高速的網絡,但你的用戶也許不是。

  • repository應該指派一個可以用作single source of truth的數據源。每當app需要獲取一塊數據的時候,它總是來自這個single source of truth。更多的信息參見上面的Single source of truth。

附:暴露網絡狀態

在前面app架構推薦一節中,為了保持例子的簡單,我們有意省略了網絡錯誤以及加載狀態。這一節我們將演示一種暴露網絡狀態的方法,使用一個Resource類來封裝數據以及數據的狀態。

下面是一個實現的例子:

<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>

因為從網絡加載數據而顯示從磁盤讀出的數據是一種常見的用例,我們將創建一個可以在多個地方重用的helper類:NetworkBoundResource。

下面是NetworkBoundResource的決策樹:

network-bound-resource.png

首先從監聽database獲取resource開始。當第一次從數據庫加載的時候,NetworkBoundResource檢查得到的結果是否可以分發或者需要從網絡獲取。注意這兩者可能同時發生,因為當從網絡更新緩存數據的時候往往還需要顯示數據。

如果網絡調用成功完成,將響應結果保存到數據庫中,然后重新初始化數據流。如果請求失敗,我們直接發出一個錯誤信號。

下面是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>

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

同時注意上面的代碼使用了 ApiResponse 作為網絡請求, ApiResponse 是對Retrofit2.Call 類的簡單封裝,用于將其響應轉換為LiveData。

下面是NetworkBoundResource類其余的實現:

<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>

現在我們就可以在repository中使用NetworkBoundResource來寫實現用戶的磁盤和網絡操作了。

<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


本頁內容由塔燈網絡科技有限公司通過網絡收集編輯所得,所有資料僅供用戶學習參考,本站不擁有所有權,如您認為本網頁中由涉嫌抄襲的內容,請及時與我們聯系,并提供相關證據,工作人員會在5工作日內聯系您,一經查實,本站立刻刪除侵權內容。本文鏈接:http://www.kwpm.com.cn/11777.html
相關APP開發
 八年  行業經驗

多一份參考,總有益處

聯系深圳網站公司塔燈網絡,免費獲得網站建設方案及報價

咨詢相關問題或預約面談,可以通過以下方式與我們聯系

業務熱線:余經理:13699882642

Copyright ? 2013-2018 Tadeng NetWork Technology Co., LTD. All Rights Reserved.    

主站蜘蛛池模板: 2020亚洲欧美日韩在线观看 | 日韩 国产 欧美 精品 在线 | 国产成人不卡亚洲精品91 | 欧美日韩一区二区在线观看 | 男女性刺激爽爽免费视频 | 草草精品视频 | 一区二区在线视频 | 色综合五月激情综合色一区 | 涩涩污 | 色视频线观看在线播放 | 天天射天天做 | 成人黄网大全在线观看 | 日韩看片| 国产v亚洲v天堂无码 | 手机在线观看你懂得 | 亚洲男女免费视频 | 日本欧美久久久久免费播放网 | 182tv午夜精品视频在线播放 | 日韩免费一区二区三区在线 | 波多野结衣免费免费视频一区 | 天天操天天草 | 福利午夜视频 | 亚洲欧美在线一区 | 中国一级毛片特级毛片 | 色网在线视频 | 99九九精品免费视频观看 | 最近中文字幕大全 | 一级黄色毛片视频 | 一个人看的www视频在线 | 成人爱做日本视频免费 | 色综合天天娱乐综合网 | 国产大臿蕉香蕉大视频女 | 成人免费国产欧美日韩你懂的 | 精品欧美一区二区在线观看 | 妞干网手机免费视频 | 久久午夜国产片 | 国产乱码精品一区二区三区网页版 | 精品国产欧美一区二区三区成人 | 99色网站| 日韩亚洲欧美综合 | 美女图片在线视频精品播放 |