Android Room
provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.
Room Persistence Library  |  Android Developers #Android_Architecture_Components
Room は、最小限のボイラープレート コードを使用してローカルデータを永続化するオブジェクト マッピング ライブラリです。コンパイル時に各クエリをデータスキーマに照らして検証することで、不完全な SQL クエリがランタイム エラーではなくコンパイル時エラーになるようにします
アプリのアーキテクチャ ガイド  |  Android Developersより
実装方針
Your Room database class must be abstract and extend RoomDatabase. Usually, you only need one instance of a Room database for the whole app.
Android Room with a View - Kotlin
例えば、insert(word)をしたいとする
viewModel.insert(word)みたいに activity(fragment)上の viewModelへのinsertメッセージ
repository.insert(word) みたいに viewModel上にあるメソッドのscopeで insert メッセージ
wordDao.insert(word)みたいに repository(Daoを引数にとってプロパティ化して Daoに insertメッセージ
移譲をしてる?でいいのかな。
1つ新しい操作をしたいとしたら、
repositoryクラス上で、Daoのinterfaceに SQLを書いて定義
ViewModelクラス上で、
abstract method (DAOを返す)
singletonで、データベースインスタンスを返す @Volatile, sychronized(this){... が慣れてない部分 JVM Synchronization
code: database_sigleton.kt
@Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(context: Context, scope: CoroutineScope): WordRoomDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
Room.databaseBuilder(context.applicationContext, WordRoomDatabase::class.java, "word_database")
.addCallback(WordDatabaseCallback(scope))
.build().also{
INSTANCE = it
}
}
}
という方針
Android Architecture Componentsでは、
roomでDatabase インスタンスを作成
インスタンスのメソッドで、abstract で 設定してあるDaoを呼ぶ。
そのDaoをinterface で定義しておいたメソッド(sqlと結びついてる?)で実際のDataBaseに対する操作
Firestoreとの住み分け、併用、このあたりのポイントは?
原則としては、FireStoreにはoffline persistanceがあるので、Roomは要らない?
ただ、併用するメリットはある?
通常のFireStoreのpersistanceは、LRUキャッシュ?それを超えてlocalに持ちたい?状況がありえる?
Cloud Firestore + Android is easy - ProAndroidDev
RealmとRoom(SQLite)との比較。説明がまとまってる。
Realmと使うAndroid Architecture Components #Android_Architecture_Components
Realmを使う際は、Android ViewModelにRealmインスタンスのライフサイクルを管理させ、ViewModelが破棄されるタイミングでRealmインスタンスをcloseさせるという使い方ができます
codelabがあるので、一度やっておく。
Android Room with a View - Kotlin