Adds MonsterRepository to manage access to the RoomDB store.

This commit is contained in:
2021-04-30 23:53:38 -07:00
parent 252dfc2630
commit be6656e219
2 changed files with 68 additions and 0 deletions

View File

@@ -10,6 +10,13 @@ import com.majinnaibu.monstercards.data.MonsterRepository;
public class MonsterCardsApplication extends Application { public class MonsterCardsApplication extends Application {
private AppDatabase m_db;
private MonsterRepository m_monsterLibraryRepository;
public MonsterRepository getMonsterRepository() {
return m_monsterLibraryRepository;
}
public static MonsterCardsApplication getInstance(Context context) { public static MonsterCardsApplication getInstance(Context context) {
return (MonsterCardsApplication) context.getApplicationContext(); return (MonsterCardsApplication) context.getApplicationContext();
} }
@@ -25,6 +32,8 @@ public class MonsterCardsApplication extends Application {
super.onCreate(); super.onCreate();
// Required initialization logic here! // Required initialization logic here!
m_db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "monsters").build();
m_monsterLibraryRepository = new MonsterRepository(m_db);
} }
// Called by the system when the device configuration changes while your component is running. // Called by the system when the device configuration changes while your component is running.

View File

@@ -0,0 +1,59 @@
package com.majinnaibu.monstercards.data;
import androidx.annotation.NonNull;
import com.majinnaibu.monstercards.AppDatabase;
import com.majinnaibu.monstercards.models.Monster;
import java.util.List;
import java.util.UUID;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class MonsterRepository {
private AppDatabase m_db;
public MonsterRepository(@NonNull AppDatabase db) {
m_db = db;
}
public Flowable<List<Monster>> getMonsters() {
return m_db.monsterDAO()
.getAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public Flowable<Monster> getMonster(UUID monsterId) {
return m_db.monsterDAO()
.loadAllByIds(new String[]{monsterId.toString()})
.map(
monsters -> {
if (monsters.size() > 0) {
return monsters.get(0);
} else {
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public Completable addMonster(Monster monster) {
Completable result = m_db.monsterDAO().insertAll(monster);
result.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
return result;
}
public Completable deleteMonster(Monster monster) {
Completable result = m_db.monsterDAO().delete(monster);
result.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
return result;
}
}