In my case saved data can be cleaned without fear in case of model changes, there is a better way to do this ?
private val dataSource = try {
MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
} catch (e: Exception) {
BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
}
I'm wondering if there is such a thing as this: https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.Builder#fallbackToDestructiveMigration()
This approach is a bit hacky, but why not!? I mean, if you don't care about loosing existing data...
Two possible refinements I can suggest:
boxFor()
should be outside the try
because any error here would be unrelated to model changes.Exception
, you could be more specific. E.g. DbSchemaException
for model related exceptions, or as an "in-between" solution, DbException
for catching any DB-related exceptions (including DbSchemaException
).So, to adapt your code it could look like this:
private val store = try {
MyObjectBox.builder().androidContext(context).build()
} catch (e: DbSchemaException) {
BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
MyObjectBox.builder().androidContext(context).build()
}
private val box = store.boxFor(XXXX::class)