2017-10-08 111 views
0

我們有多個相互獨立的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; 
} 
+0

什麼是做單MigrationManager一切的問題呢? – algrid

+0

遵循複合設計模式,就像我在https://stackoverflow.com/a/45592632/2413303中提到的多個initialData()一樣 – EpicPandaForce

回答

2

您可以創建一個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); 
     } 
    } 
}