如何支持多个 RealmMigrations
How to support multiple RealmMigrations
我们有多个 android 库,它们彼此独立并依赖于核心库。核心库有CoreRealmManager,负责所有领域操作。
app
| --- lib-module-a
| \-- lib-module-c
| \-- lib-core
|
| -x- lib-module-b
| \-- lib-core
|
| --- lib-module-c
| \-- lib-core
|
| --- lib-module-d
| \-- lib-core
|
| --- lib-core
这些库可以有选择地添加到应用程序中,并且应用程序也可以有 RealmClasses。初始化时每个库在调用领域之前调用 CoreRealmManager.addModule(Object additionalModule)
。
如果多个库和应用程序想要迁移,则在给定时间点。如何实现?
Realm 仅支持 Single RealmMigration。
@NonNull
static RealmConfiguration.Builder getConfigBundle() {
RealmConfiguration.Builder builder = new RealmConfiguration.Builder();
builder.schemaVersion(DB_VERSION)
.modules(Realm.getDefaultModule(),
// Add additional library modules
getAdditionalModules());
if (BuildConfig.DEBUG) {
builder.deleteRealmIfMigrationNeeded();
} else {
// Set migration manager
builder.migration(new MigrationManager()); // <-- Support multiple migration manager?
byte[] secretKey = getSecretKey();
if (secretKey != null) {
builder.encryptionKey(secretKey);
}
}
return builder;
}
您可以创建一个 MigrationManager
来处理迁移列表,然后让每个子模块向其注册自己的迁移。
类似
public class MigrationManager implements RealmMigration {
List<RealmMigration> migrations = new ArrayList<>();
public void addMigration(RealmMigration migration) {
migrations.add(migration);
}
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
for (RealmMigration migration : migrations) {
migration.migrate(realm, oldVersion, newVersion);
}
}
}
我们有多个 android 库,它们彼此独立并依赖于核心库。核心库有CoreRealmManager,负责所有领域操作。
app | --- lib-module-a | \-- lib-module-c | \-- lib-core | | -x- lib-module-b | \-- lib-core | | --- lib-module-c | \-- lib-core | | --- lib-module-d | \-- lib-core | | --- lib-core
这些库可以有选择地添加到应用程序中,并且应用程序也可以有 RealmClasses。初始化时每个库在调用领域之前调用 CoreRealmManager.addModule(Object additionalModule)
。
如果多个库和应用程序想要迁移,则在给定时间点。如何实现? Realm 仅支持 Single RealmMigration。
@NonNull
static RealmConfiguration.Builder getConfigBundle() {
RealmConfiguration.Builder builder = new RealmConfiguration.Builder();
builder.schemaVersion(DB_VERSION)
.modules(Realm.getDefaultModule(),
// Add additional library modules
getAdditionalModules());
if (BuildConfig.DEBUG) {
builder.deleteRealmIfMigrationNeeded();
} else {
// Set migration manager
builder.migration(new MigrationManager()); // <-- Support multiple migration manager?
byte[] secretKey = getSecretKey();
if (secretKey != null) {
builder.encryptionKey(secretKey);
}
}
return builder;
}
您可以创建一个 MigrationManager
来处理迁移列表,然后让每个子模块向其注册自己的迁移。
类似
public class MigrationManager implements RealmMigration {
List<RealmMigration> migrations = new ArrayList<>();
public void addMigration(RealmMigration migration) {
migrations.add(migration);
}
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
for (RealmMigration migration : migrations) {
migration.migrate(realm, oldVersion, newVersion);
}
}
}