我是android的初学者。我正在尝试使用新的Android MVVM架构开发应用程序。参考以下GitHub的谷歌示例代码:
https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample
我正在使用Room,Data Binding,Retrofit,Dagger 2
我开发的My List Activity在上面的架构中运行良好
我的API电影列表响应:
[
{
id : 1,
name : "ABC"
},
{
id : 2,
name : "XYZ"
}
]
但我面临细节活动的问题 我的电影细节API响应是:
{
id:1,
name : "ABC",
sources : [
{
sourceId : 1,
sourceName : "Source Name 1"
},
{
sourceId : 2,
sourceName : "Source Name 2"
}]
}
在我的应用中,我有2个实体 1.MovieEntity 2.MovieSourceEntity
删除我的存储库代码:
public LiveData<Resource<MovieEntity>> loadRepo(String id) {
return new NetworkBoundResource<MovieEntity, MovieEntity>(appExecutors) {
@Override
protected void saveCallResult(@NonNull MovieEntity item) {
movieDao.insert(item);
movieDao.insertSources(item.getSources());
}
@Override
protected boolean shouldFetch(@Nullable MovieEntity data) {
return data == null;
}
@NonNull
@Override
protected LiveData<MovieEntity> loadFromDb() {
return movieDao.load(id);
}
@NonNull
@Override
protected LiveData<ApiResponse<MovieEntity>> createCall() {
return movieService.getRepo(id);
}
}.asLiveData();
}
此代码仅返回MovieEntity数据loadFromDb未返回MovieSourceEntity ListOfData任何人都知道如何实现此目的
答案
public LiveData<Resource<MovieDetailEntity>> loadMovie(Integer id) {
return new NetworkBoundResource<MovieDetailEntity, MovieEntity>(appExecutors) {
@Override
protected void saveCallResult(@NonNull MovieEntity item) {
movieDao.saveMovie(item);
movieDao.saveMovieSources(item.getSources());
}
@Override
protected boolean shouldFetch(@Nullable MovieDetailEntity data) {
return data ==null || data.getSources() == null || data.getSources().isEmpty();
}
@NonNull
@Override
protected LiveData<MovieDetailEntity> loadFromDb() {
LiveData<MovieDetailEntity> movieEntity = movieDao.loadMovieDetail(id);
return movieEntity;
}
@NonNull
@Override
protected LiveData<ApiResponse<MovieEntity>> createCall() {
return movieDBService.loadMovie(id);
}
}.asLiveData();
}