如何支持多种Realmigrations
问题描述:
我们有多个相互独立的android库依靠核心库。核心库有CoreRealmManager,它负责所有领域的操作。如何支持多种Realmigrations
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仅支持单个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);
}
}
}
什么是做单MigrationManager一切的问题呢? – algrid
遵循复合设计模式,就像我在https://stackoverflow.com/a/45592632/2413303中提到的多个initialData()一样 – EpicPandaForce