This repository has been archived by the owner on Jan 10, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 86
Database Access with Room and RxJava
Jacqueline Bronger edited this page May 1, 2018
·
4 revisions
Since version 1.5.2 we no longer use any cursors or raw db queries but instead Room.
For most cases nothing has changed and you can use the manager as usual, however the goal is to implement MVVM for every ui. Activities that already implement MVVM:
- KinoActivity
- MensaActivity
The following diagram shows the architecture for MVVM enabled Activites
- Provides abstraction layer over SQLite
- More efficient way of retrieving data from database ⇒ less code ⇒ fewer bugs
- Tables: Each class annotated with @Entity
- Data Access Objects (DAOs): Responsible for defining the methods that access the database (Annotations: @Query @Update @Delete)
- Database: Class annotated with @Database, lists all entities contained in the database, and the DAOs which access them.
- RxJava is an implementation of http://reactivex.io/ for Java, which provides an API for asynchronous programming with observable streams.
- We use RxJava in combination with Room to get so called Flowables. A Flowable is an Observable that emits items whenever the data is changed in the database (and oc initially)
- Also with rxjava no work is done on the ui thread, only the code that is within the subscribe method.
Further resources:
A: Depends on whether we already introduced RxJava for this or not.
- Without RxJava and if there is a corresponding manager:
protected void onStart() {
super.onStart();
// Gets all news from database
nm = new NewsManager(this);
List<News> news = nm.getAllFromDb(this);
...
}
- Without RxJava and without corresponding manager:
protected void onStart() {
super.onStart();
calendarDao = TcaDb.getInstance(context).calendarDao();
calendarItems = calendarDao.getAllByDateNotCancelled(Utils.getDateString(new Date()));
...
}
- With RxJava:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
KinoLocalRepository.db = TcaDb.getInstance(this);
kinoViewModel = new KinoViewModel(KinoLocalRepository.INSTANCE, KinoRemoteRepository.INSTANCE, disposable);
...
}
@Override
protected void onStart() {
super.onStart();
//access:
kinoViewModel.getAllKinos()
.doOnError(throwable -> setContentView(R.layout.layout_error))
.subscribe(kinos -> {
//Do what you want to do with the data
});
}
Location of Migrations and the Database:
Location of available viewmodels (or RxJava integrations for Cafeteria)
Corresponding repositories for RxJava ViewModels (for Cafeteria)