我有LiveData
使用ViewModel,其中包含Service
,应该从前景LiveData
进行修改。
我需要的是:
从Activity
观察到Service
,因此当从MutableLiveData
修改后,会更新用户界面。要使其工作,应以某种方式使用LiveData
。
我应该将Room
存储在_, encoded_img = cv2.imencode('.jpg', img, [ int( cv2.IMWRITE_JPEG_QUALITY ), 95 ] )
数据库中,还是针对此问题提供更优雅的解决方案?
如果使用Room是一个解决方案,如何存储和更新单一且唯一的实体?
答案 0 :(得分:0)
根据推荐的Android架构,您应该有一个Repository
,这只是一个负责向ViewModel
提供数据的类,存储库从Room database
获取数据并提示服务刷新进入数据库。从RoomDB获取的数据是实时数据,一旦被服务更新,其观察者就会被解雇。 Android architecture components
public class MovieRepository {
private static final String language = "en-US";
private static final String sortBy = "popularity.desc";
private static final String includeAdult = "false";
private static final String includeVideo = "false";
private static final String page = "1";
Resources mResources;
MovieDatabase mMovieDatabase;
MoviesInterfaceImpl mMoviesInterface;
MoviesWatchApplication mMoviesWatchApplication;
public MovieRepository(MovieDatabase movieDatabase,
MoviesInterfaceImpl moviesInterface,
MoviesWatchApplication moviesWatchApplication) {
mMovieDatabase = movieDatabase;
mMoviesInterface = moviesInterface;
mMoviesWatchApplication = moviesWatchApplication;
}
public LiveData<List<Movie>> getMovies() {
mResources = mMoviesWatchApplication.getApplicationContext().getResources();
refreshMovies();
LiveData<List<Movie> > movies = mMovieDatabase.movieDao().getMovies();
return movies;
}
private void refreshMovies () {
mMoviesInterface.discoverMovies(
mResources.getString(R.string.api_key),
language, sortBy, includeAdult, includeVideo , page
).enqueue(new Callback<DiscoverResponse>() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onResponse(Call<DiscoverResponse> call, Response<DiscoverResponse> response) {
if(response.code() == 200) {
List<Movie> movieList = new ArrayList<>();
response.body().getResults().forEach((result) -> {
Movie movie = new Movie(result);
movieList.add(movie);
});
mMovieDatabase.movieDao().addMovies(movieList);
}
}
@Override
public void onFailure(Call<DiscoverResponse> call, Throwable t) {
}
});
}
}