最近,官方推出了一份關(guān)于應(yīng)用架構(gòu)的最佳實(shí)踐指南。這里就給大家簡要介紹一下:
首先,Android 開發(fā)者肯定都知道 Android 中有四大組件,這些組件都有各自的生命周期并且在一定程度上是不受你控制的。在任何時(shí)候,Android 操作系統(tǒng)都可能根據(jù)用戶的行為或資源緊張等原因回收掉這些組件。
這也就引出了第一條準(zhǔn)則:「不要在應(yīng)用程序組件中保存任何應(yīng)用數(shù)據(jù)或狀態(tài),并且組件間也不應(yīng)該相互依賴」。
最常見的錯(cuò)誤就是在 Activity 或 Fragment 中寫了與 UI 和交互無關(guān)的代碼。盡可能減少對它們的依賴,這能避免大量生命周期導(dǎo)致的問題,以提供更好的用戶體驗(yàn)。
第二條準(zhǔn)則:「通過 model 驅(qū)動應(yīng)用 UI,并盡可能的持久化」。
這樣做主要有兩個(gè)原因:
如果系統(tǒng)回收了你的應(yīng)用資源或其他什么意外情況,不會導(dǎo)致用戶丟失數(shù)據(jù)。
Model 就應(yīng)該是負(fù)責(zé)處理應(yīng)用程序數(shù)據(jù)的組件。獨(dú)立于視圖和應(yīng)用程序組件,保持了視圖代碼的簡單,也讓你的應(yīng)用邏輯更容易管理。并且,將應(yīng)用數(shù)據(jù)置于 model 類中,也更有利于測試。
官方推薦的 App 架構(gòu)
在這里,官方演示了通過使用最新推出的 Architecture Components 來構(gòu)建一個(gè)應(yīng)用。
想象一下,您正在打算開發(fā)一個(gè)顯示用戶個(gè)人信息的界面,用戶數(shù)據(jù)通過 REST API 從后端獲取。
首先,我們需要?jiǎng)?chuàng)建三個(gè)文件:
user_profile.xml:定義界面。
UserProfileViewModel.java:數(shù)據(jù)類。
UserProfileFragment.java:顯示 ViewModel 中的數(shù)據(jù)并對用戶的交互做出反應(yīng)。
為了簡單起見,我們這里就省略掉布局文件。
代碼
public class UserProfileViewModel extends ViewModel {
private String userId;
private User user;
public void init(String userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
}
代碼
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);
}
}
注意其中的 ViewModel 和 LifecycleFragment 都是 Android 新引入的,可以參考官方說明進(jìn)行集成。
現(xiàn)在,我們完成了這三個(gè)模塊,該如何將它們聯(lián)系起來呢?也就是當(dāng) ViewModel 中的用戶字段被設(shè)置時(shí),我們需要一種方法來通知 UI。這就是 LiveData 的用武之地了。
引用
LiveData 是一個(gè)可被觀察的數(shù)據(jù)持有者(用到了觀察者模式)。其能夠允許 Activity, Fragment 等應(yīng)用程序組件對其進(jìn)行觀察,并且不會在它們之間創(chuàng)建強(qiáng)依賴。LiveData 還能夠自動響應(yīng)各組件的聲明周期事件,防止內(nèi)存泄漏,從而使應(yīng)用程序不會消耗更多的內(nèi)存。
注意: LiveData 和 RxJava 或 Agera 的區(qū)別主要在于 LiveData 自動幫助處理了生命周期事件,避免了內(nèi)存泄漏。
所以,現(xiàn)在我們來修改一下 UserProfileViewModel:
代碼
public class UserProfileViewModel extends ViewModel {
...
private LiveData<User> user;
public LiveData<User> getUser() {
return user;
}
}
再在 UserProfileFragment 中對其進(jìn)行觀察并更新我們的 UI:
代碼
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel.getUser().observe(this, user -> {
// update UI
});
}
獲取數(shù)據(jù)
現(xiàn)在,我們聯(lián)系了 ViewModel 和 Fragment,但 ViewModel 又怎么來獲取到數(shù)據(jù)呢?
在這個(gè)示例中,我們假定后端提供了 REST API,因此我們選用 Retrofit 來訪問我們的后端。
首先,定義一個(gè) Webservice:
代碼
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);
}
不要通過 ViewModel 直接來獲取數(shù)據(jù),這里我們將工作轉(zhuǎn)交給一個(gè)新的 Repository 模塊。
引用
Repository 模塊負(fù)責(zé)數(shù)據(jù)處理,為應(yīng)用的其他部分提供干凈可靠的 API。你可以將其考慮為不同數(shù)據(jù)源(Web,緩存或數(shù)據(jù)庫)與應(yīng)用之間的中間層。
代碼
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;
}
}
管理組件間的依賴關(guān)系
根據(jù)上面的代碼,我們可以看到 UserRepository 中有一個(gè) Webservice 的實(shí)例,不要直接在 UserRepository 中 new 一個(gè) Webservice。這很容易導(dǎo)致代碼的重復(fù)與復(fù)雜化,比如 UserRepository 很可能不是唯一用到 Webservice 的類,如果每個(gè)用到的類都新建一個(gè) Webservice,這顯示會導(dǎo)致資源的浪費(fèi)。
這里,我們推薦使用 Dagger 2 來管理這些依賴關(guān)系。
現(xiàn)在,讓我們來把 ViewModel 和 Repository 連接起來吧:
代碼
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;
}
}
緩存數(shù)據(jù)
在實(shí)際項(xiàng)目中,Repository 往往不會只有一個(gè)數(shù)據(jù)源。因此,我們這里在其中再加入緩存:
代碼
@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;
}
}
持久化數(shù)據(jù)
現(xiàn)在當(dāng)用戶旋轉(zhuǎn)屏幕或暫時(shí)離開應(yīng)用再回來時(shí),數(shù)據(jù)是直接可見的,因?yàn)槭侵苯訌木彺嬷蝎@取的數(shù)據(jù)。但要是用戶長時(shí)間關(guān)閉應(yīng)用,并且 Android 還徹底殺死了進(jìn)程呢?
我們目前的實(shí)現(xiàn)中,會再次從網(wǎng)絡(luò)中獲取數(shù)據(jù)。這可不是一個(gè)好的用戶體驗(yàn)。這時(shí)就需要數(shù)據(jù)持久化了。繼續(xù)引入一個(gè)新組件 Room。
引用
Room 能幫助我們方便的實(shí)現(xiàn)本地?cái)?shù)據(jù)持久化,抽象出了很多常用的數(shù)據(jù)庫操作,并且在編譯時(shí)會驗(yàn)證每個(gè)查詢,從而損壞的 SQL 查詢只會導(dǎo)致編譯時(shí)錯(cuò)誤,而不是運(yùn)行時(shí)崩潰。還能和上面介紹的 LiveData 完美合作,并幫開發(fā)者處理了很多線程問題。
現(xiàn)在,讓我們來看看怎么使用 Room 吧。: )
首先,在 User 類上面加上 @Entity,將 User 聲明為你數(shù)據(jù)庫中的一張表。
代碼
@Entity
class User {
@PrimaryKey
private int id;
private String name;
private String lastName;
// getters and setters for fields
}
再創(chuàng)建數(shù)據(jù)庫類并繼承 RoomDatabase:
代碼
@Database(entities = {User.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
}
注意 MyDatabase 是一個(gè)抽象類,Room 會自動添加實(shí)現(xiàn)的。
現(xiàn)在我們需要一種方法來將用戶數(shù)據(jù)插入到數(shù)據(jù)庫:
代碼
@Dao
public interface UserDao {
@Insert(onConflict = REPLACE)
void save(User user);
@Query("SELECT * FROM user WHERE id = :userId")
LiveData<User> load(String userId);
}
再在數(shù)據(jù)庫類中加入 DAO:
代碼
@Database(entities = {User.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
注意上面的 load 方法返回的是 LiveData,Room 會知道什么時(shí)候數(shù)據(jù)庫發(fā)生了變化并自動通知所有的觀察者。這也就是 LiveData 和 Room 搭配的妙用。
現(xiàn)在繼續(xù)修改 UserRepository:
代碼
@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());
}
});
}
}
可以看到,即使我們更改了 UserRepository 中的數(shù)據(jù)源,我們也完全不需要修改 ViewModel 和 Fragment,這就是抽象的好處。同時(shí)還非常適合測試,我們可以在測試 UserProfileViewModel 時(shí)提供測試用的 UserRepository。
引用
下面部分的內(nèi)容在原文中是作為附錄,但我個(gè)人覺得也很重要,所以擅自挪上來,一起為大家介紹了。: )
在上面的例子中,有心的大家可能發(fā)現(xiàn)了我們沒有處理網(wǎng)絡(luò)錯(cuò)誤和正在加載狀態(tài)。但在實(shí)際開發(fā)中其實(shí)是很重要的。這里,我們就實(shí)現(xiàn)一個(gè)工具類來根據(jù)不同的網(wǎng)絡(luò)狀況選擇不同的數(shù)據(jù)源。
首先,實(shí)現(xiàn)一個(gè) Resource 類:
代碼
//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);
}
}
因?yàn)?,從網(wǎng)絡(luò)加載數(shù)據(jù)和從磁盤加載是很相似的,所以再新建一個(gè) NetworkBoundResource 類,方便多處復(fù)用。下面是 NetworkBoundResource 的決策樹:
API 設(shè)計(jì):
代碼
// 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;
}
}
注意上面使用了 ApiResponse 作為網(wǎng)絡(luò)請求, ApiResponse 是對于 Retrofit2.Call 的簡單包裝,用于將其響應(yīng)轉(zhuǎn)換為 LiveData。
下面是具體的實(shí)現(xiàn):
代碼
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();
}
}
現(xiàn)在,我們就能使用 NetworkBoundResource 來根據(jù)不同的情況獲取數(shù)據(jù)了:
代碼
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();
}
}
到這里,我們的代碼就全部完成了。最后的架構(gòu)看起來就像這樣:
最后的最后,給出一些指導(dǎo)原則
下面的原則雖然不是強(qiáng)制性的,但根據(jù)我們的經(jīng)驗(yàn)遵循它們能使您的代碼更健壯、可測試和可維護(hù)的。
所有您在 manifest 中定義的組件 - activity, service, broadcast receiver… 都不是數(shù)據(jù)源。因?yàn)槊總€(gè)組件的生命周期都相當(dāng)短,并取決于當(dāng)前用戶與設(shè)備的交互和系統(tǒng)的運(yùn)行狀況。簡單來說,這些組件都不應(yīng)當(dāng)作為應(yīng)用的數(shù)據(jù)源。
在您應(yīng)用的各個(gè)模塊之間建立明確的責(zé)任邊界。比如,不要將與數(shù)據(jù)緩存無關(guān)的代碼放在同一個(gè)類中。
每個(gè)模塊盡可能少的暴露內(nèi)部實(shí)現(xiàn)。從過去的經(jīng)驗(yàn)來看,千萬不要為了一時(shí)的方便而直接將大量的內(nèi)部實(shí)現(xiàn)暴露出去。這會讓你在以后承擔(dān)很重的技術(shù)債務(wù)(很難更換新技術(shù))。
在您定義模塊間交互時(shí),請考慮如何使每個(gè)模塊盡量隔離,通過設(shè)計(jì)良好的 API 來進(jìn)行交互。
您應(yīng)用的核心應(yīng)該是能讓它脫穎而出的某些東西。不要浪費(fèi)時(shí)間重復(fù)造輪子或一次次編寫同樣的模板代碼。相反,應(yīng)當(dāng)集中精力在使您的應(yīng)用獨(dú)一無二,而將一些重復(fù)的工作交給這里介紹的 Android Architecture Components 或其他優(yōu)秀的庫。
盡可能持久化數(shù)據(jù),以便您的應(yīng)用在脫機(jī)模式下依然可用。雖然您可能享受著快捷的網(wǎng)絡(luò),但您的用戶可能不會。