仅为调试构建添加房间数据库迁移
Add room DB migration only for Debug build
我创建数据库的函数是这样的:
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also { instance = it }
}
并建立数据库:
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "Rides.db")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.build()
我需要的是MIGRATION_2_3只会在调试模式下发生,像这样(伪):
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "Rides.db")
.addMigrations(MIGRATION_1_2)
if (BuildConfig.Debug)
{
.addMigrations(MIGRATION_2_3)
}
.build()
}
在不创建两个 buildDatabase 函数的情况下实现此目的的正确语法是什么?
您已经提到了它的伪代码。您可以获得构建器并添加条件,然后 return builder.build()
.
private fun buildDatabase(context: Context):AppDatabase {
val builder = Room.databaseBuilder(
context,
AppDatabase::class.java, "Rides.db"
)
.addMigrations(MIGRATION_1_2)
if (BuildConfig.DEBUG) {
builder.addMigrations(MIGRATION_2_3)
}
return builder.build()
}
或
private fun buildDatabase(context: Context): AppDatabase =
Room.databaseBuilder(
context,
AppDatabase::class.java, "Rides.db"
).apply {
addMigrations(MIGRATION_1_2)
if (BuildConfig.DEBUG) {
addMigrations(MIGRATION_2_3)
}
}.build()
我创建数据库的函数是这样的:
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also { instance = it }
}
并建立数据库:
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "Rides.db")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.build()
我需要的是MIGRATION_2_3只会在调试模式下发生,像这样(伪):
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "Rides.db")
.addMigrations(MIGRATION_1_2)
if (BuildConfig.Debug)
{
.addMigrations(MIGRATION_2_3)
}
.build()
}
在不创建两个 buildDatabase 函数的情况下实现此目的的正确语法是什么?
您已经提到了它的伪代码。您可以获得构建器并添加条件,然后 return builder.build()
.
private fun buildDatabase(context: Context):AppDatabase {
val builder = Room.databaseBuilder(
context,
AppDatabase::class.java, "Rides.db"
)
.addMigrations(MIGRATION_1_2)
if (BuildConfig.DEBUG) {
builder.addMigrations(MIGRATION_2_3)
}
return builder.build()
}
或
private fun buildDatabase(context: Context): AppDatabase =
Room.databaseBuilder(
context,
AppDatabase::class.java, "Rides.db"
).apply {
addMigrations(MIGRATION_1_2)
if (BuildConfig.DEBUG) {
addMigrations(MIGRATION_2_3)
}
}.build()