Repository : mediators between different data sources (persistent model, web service, cache)
简言之,是一个数据总管家,知道从何处(persistent, web, cache)获取数据并调用相关API更新数据,封装了处理的过程,仅向app的其它部分提供数据,这意味着可以在不修改app其它部分的前提下修改数据处理的部分。
Repository modules are responsible for handling data operations. They provide a clean API to the rest of the app. They know where to get the data from and what API calls to make when data is updated. You can consider them as mediators between different data sources (persistent model, web service, cache, etc.).
It serves an important purpose; it abstracts the data sources from the rest of the app. Now our ViewModel does not know that the data is fetched by the Webservice, which means we can swap it for other implementations as necessary.
@Singleton
public class DemoRepository {
@Inject
ArticleDao mArticleDao;
@Inject
DemoWebService mDemoWebService;
@Inject
public DemoRepository(){
}
public LiveData<Resource<List<Article>>> loadArticleList() {
return new NetworkBoundResource<List<Article>, List<Article>>(mExecutors) {
/**
* Called to save the result of the API response into the database
*/
@Override
protected void saveCallResult(@NonNull List<Article> articles) {
// Insert new article data into the database
mArticleDao.bulkInsert(articles.toArray(new Article[articles.size()]));
Log.d(LOG_TAG, "new values inserted");
}
/**
* Called with the data in the database to decide whether it should be fetched from the network.
*/
@Override
protected boolean shouldFetch(@Nullable List<Article> data) {
return data == null || data.isEmpty() || repoListRateLimit.shouldFetch(LOG_TAG);
}
/**
* Called to get the cached data from the database
*/
@NonNull
@Override
protected LiveData<List<Article>> loadFromDb() {
return mArticleDao.getArticleList();
}
/**
* Called to create the web service API call.
*/
@NonNull
@Override
protected LiveData<ApiResponse<List<Article>>> createCall() {
return mDemoWebService.getArticleList();
}
@Override
protected void onFetchFailed() {
repoListRateLimit.reset(LOG_TAG);
}
}.asLiveData();
}
public LiveData<Article> loadArticle(int id) {
return mArticleDao.getArticle(id);
}