国产亚洲欧美人成在线,免费视频爱爱太爽了无码,日本免费一区二区三区高清视频 ,国产真实伦对白精彩视频

歡迎您光臨深圳塔燈網(wǎng)絡(luò)科技有限公司!
電話圖標(biāo) 余先生:13699882642

網(wǎng)站百科

為您解碼網(wǎng)站建設(shè)的點點滴滴

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

發(fā)表日期:2018-04 文章編輯:小燈 瀏覽次數(shù):1354

本文轉(zhuǎn)載自:鏈接

這篇文章面向的是已經(jīng)掌握app開發(fā)基本知識,想知道如何開發(fā)健壯app的讀者。

注:本指南假設(shè)讀者對 Android Framework 已經(jīng)很熟悉。如果你還是app開發(fā)的新手,請查看 Getting Started 系列教程,該教程涵蓋了本指南的預(yù)備知識。

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)用往往在一個龐大的單一的進程中就完成了。

大多數(shù)的app組件都聲明在app manifest中,Android OS用它來決定如何將你的app與設(shè)備整合形成統(tǒng)一的用戶體驗。雖然就如剛說的,桌面app只運行一個進程,但是一個優(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是負責(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殺死了你的進程,這個數(shù)據(jù)可以被保存下來,所以app再次啟動的時候id仍是可用的。

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

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

一個ViewModel為特定的UI組件提供數(shù)據(jù),比如fragment 或者 activity,并負責(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)(為簡單起見,省略了布局文件):

1.public class UserProfileViewModel extends ViewModel { 2.private String userId; 3.private User user;5.public void init(String userId) { 6.this.userId = userId; 7.} 8.public User getUser() { 9.return user; 10.} 11.} 
1.public class UserProfileFragment extends LifecycleFragment { 2.private static final String UID_KEY = "uid"; 3.private UserProfileViewModel viewModel;5.@Override 6.public void onActivityCreated(@Nullable Bundle savedInstanceState) { 7.super.onActivityCreated(savedInstanceState); 8.String userId = getArguments().getString(UID_KEY); 9.viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class); 10.viewModel.init(userId); 11.}13.@Override 14.public View onCreateView(LayoutInflater inflater, 15.@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 16.return inflater.inflate(R.layout.user_profile, container, false); 17.} 18.} 

注:上面的例子中繼承的是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ù)流要停止,LifecycleOwnerdestroyed的時候數(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)它不再被需要的時候會自動清理引用。

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

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

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

每當(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進入生命周期,它將收到相同的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來達到相同的目的。

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

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

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

Repository模塊負責(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ù)。

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

雖然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)造依賴的情況下定義自己的依賴對象。在運行時由另一個類來負責(zé)提供這些依賴。在Android app中我們推薦使用谷歌的Dagger 2來實現(xiàn)依賴注入。Dagger 2 通過遍歷依賴樹自動構(gòu)建對象,并提供編譯時的依賴。

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

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

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

連接ViewModel和repository

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

 1.public class UserProfileViewModel extends ViewModel { 2.private LiveData<User> user; 3.private UserRepository userRepo;5.@Inject // UserRepository parameter is provided by Dagger 2 6.public UserProfileViewModel(UserRepository userRepo) { 7.this.userRepo = userRepo; 8.}10.public void init(String userId) { 11.if (this.user != null) { 12.// ViewModel is created per Fragment so 13.// we know the userId won't change 14.return; 15.} 16.user = userRepo.getUser(userId); 17.}19.public LiveData<User> getUser() { 20.return this.user; 21.} 22.}

緩存數(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)存中。

 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.}12.final MutableLiveData<User> data = new MutableLiveData<>(); 13.userCache.put(userId, data); 14.// this is still suboptimal but better than before. 15.// a complete implementation must also handle the error cases. 16.webservice.getUser(userId).enqueue(new Callback<User>() { 17.@Override 18.public void onResponse(Call<User> call, Response<User> response) { 19.data.setValue(response.body()); 20.} 21.}); 22.return data; 23.} 24.}

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

目前的實現(xiàn)中,如果用戶旋轉(zhuǎn)屏幕或者是離開之后再次回到app,UI將立即可見,因為repository是從常駐內(nèi)存的緩存中獲取的數(shù)據(jù)。但是如果用戶離開了app,幾個小時之后再回來時進程已經(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)操作的底層細節(jié)。它還可以讓你通過一個LiveData對象監(jiān)聽到數(shù)據(jù)庫數(shù)據(jù)的變化。另外,它還明確定義了線程約束,解決了諸如從主線程獲取存儲這樣的常見的問題。

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

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

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

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

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

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

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

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

然后,在database類中引用DAO。

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

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

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

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

1.@Singleton 2.public class UserRepository { 3.private final Webservice webservice; 4.private final UserDao userDao; 5.private final Executor executor;7.@Inject 8.public UserRepository(Webservice webservice, UserDao userDao, Executor executor) { 9.this.webservice = webservice; 10.this.userDao = userDao; 11.this.executor = executor; 12.}14.public LiveData<User> getUser(String userId) { 15.refreshUser(userId); 16.// return a LiveData directly from the database. 17.return userDao.load(userId); 18.}20.private void refreshUser(final String userId) { 21.executor.execute(() -> { 22.// running in a background thread 23.// check if user was fetched recently 24.boolean userExists = userDao.hasUser(FRESH_TIMEOUT); 25.if (!userExists) { 26.// refresh the data 27.Response response = webservice.getUser(userId).execute(); 28.// TODO check for error etc. 29.// Update the database.The LiveData will automatically refresh so 30.// we don't need to do anything else here besides updating the database 31.userDao.save(response.body()); 32.} 33.}); 34.} 35.}

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

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

在某些情況下,比如下拉刷新,在界面上顯示當(dāng)前是否正在進行網(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)容詳細程度都不一樣。如果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ù)交互,還是獲取遠程數(shù)據(jù)并緩存到本地,還是一個有一定規(guī)模的app可能遇到的其它常見問題。

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

  • 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ù)綁定-放在一個類中。

  • 每個模塊暴露的細節(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)的例子:

 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.}12.public static <T> Resource<T> success(@NonNull T data) { 13.return new Resource<>(SUCCESS, data, null); 14.}16.public static <T> Resource<T> error(String msg, @Nullable T data) { 17.return new Resource<>(ERROR, data, msg); 18.}20.public static <T> Resource<T> loading(@Nullable T data) { 21.return new Resource<>(LOADING, data, null); 22.} 23.}

因為從網(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:

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);8.// Called with the data in the database to decide whether it should be 9.// fetched from the network. 10.@MainThread 11.protected abstract boolean shouldFetch(@Nullable ResultType data);13.// Called to get the cached data from the database 14.@NonNull @MainThread 15.protected abstract LiveData<ResultType> loadFromDb();17.// Called to create the API call. 18.@NonNull @MainThread 19.protected abstract LiveData<ApiResponse<RequestType>> createCall();21.// Called when the fetch fails. The child class may want to reset components 22.// like rate limiter. 23.@MainThread 24.protected void onFetchFailed() { 25.}27.// returns a LiveData that represents the resource 28.public final LiveData<Resource<ResultType>> getAsLiveData() { 29.return result; 30.} 31.}

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

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

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

 1.public abstract class NetworkBoundResource<ResultType, RequestType> { 2.private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>();4.@MainThread 5.NetworkBoundResource() { 6.result.setValue(Resource.loading(null)); 7.LiveData<ResultType> dbSource = loadFromDb(); 8.result.addSource(dbSource, data -> { 9.result.removeSource(dbSource); 10.if (shouldFetch(data)) { 11.fetchFromNetwork(dbSource); 12.} else { 13.result.addSource(dbSource, 14.newData -> result.setValue(Resource.success(newData))); 15.} 16.}); 17.}19.private void fetchFromNetwork(final LiveData<ResultType> dbSource) { 20.LiveData<ApiResponse<RequestType>> apiResponse = createCall(); 21.// we re-attach dbSource as a new source, 22.// it will dispatch its latest value quickly 23.result.addSource(dbSource, 24.newData -> result.setValue(Resource.loading(newData))); 25.result.addSource(apiResponse, response -> { 26.result.removeSource(apiResponse); 27.result.removeSource(dbSource); 28.//noinspection ConstantConditions 29.if (response.isSuccessful()) { 30.saveResultAndReInit(response); 31.} else { 32.onFetchFailed(); 33.result.addSource(dbSource, 34.newData -> result.setValue( 35.Resource.error(response.errorMessage, newData))); 36.} 37.}); 38.}40.@MainThread 41.private void saveResultAndReInit(ApiResponse<RequestType> response) { 42.new AsyncTask<Void, Void, Void>() {44.@Override 45.protected Void doInBackground(Void... voids) { 46.saveCallResult(response.body); 47.return null; 48.}50.@Override 51.protected void onPostExecute(Void aVoid) { 52.// we specially request a new live data, 53.// otherwise we will get immediately last cached value, 54.// which may not be updated with latest results received from network. 55.result.addSource(loadFromDb(), 56.newData -> result.setValue(Resource.success(newData))); 57.} 58.}.execute(); 59.} 60.}

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

1.class UserRepository { 2.Webservice webservice; 3.UserDao userDao;5.public LiveData<Resource<User>> loadUser(final String userId) { 6.return new NetworkBoundResource<User,User>() { 7.@Override 8.protected void saveCallResult(@NonNull User item) { 9.userDao.insert(item); 10.}12.@Override 13.protected boolean shouldFetch(@Nullable User data) { 14.return rateLimiter.canFetch(userId) && (data == null || !isFresh(data)); 15.}17.@NonNull @Override 18.protected LiveData<User> loadFromDb() { 19.return userDao.load(userId); 20.}22.@NonNull @Override 23.protected LiveData<ApiResponse<User>> createCall() { 24.return webservice.getUser(userId); 25.} 26.}.getAsLiveData(); 27.} 28.}

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

譯注:本文涉及到的代碼示例在https://github.com/googlesamples/android-architecture-components中都可以找到完整版本。


本頁內(nèi)容由塔燈網(wǎng)絡(luò)科技有限公司通過網(wǎng)絡(luò)收集編輯所得,所有資料僅供用戶學(xué)習(xí)參考,本站不擁有所有權(quán),如您認為本網(wǎng)頁中由涉嫌抄襲的內(nèi)容,請及時與我們聯(lián)系,并提供相關(guān)證據(jù),工作人員會在5工作日內(nèi)聯(lián)系您,一經(jīng)查實,本站立刻刪除侵權(quán)內(nèi)容。本文鏈接:http://m.jstctz.cn/12458.html
相關(guān)APP開發(fā)