Search code examples
androidrealmrealm-java

How to use two different realm configurations


I'm working with the default realm instance, which contains some schemas. Now, I want to create a new schema in a different realm instance. So I have created a new Realm configuration, and when I query or store entities for this new schema, I use the new configuration, instead of the default one. In this way, I expect to avoid the neeed of create a migration for the new schema, due to I use it with a different database. But when I use the default realm instance, an exception is thrown (RealmMigrationNeededException), which tells me that I have to create a migration for my new schema. Can I avoid that in any way if I want to work with my new schema only in a new database?


Solution

  • Check Realm's document: https://realm.io/docs/java/latest/#schemas

    You need to define your 2 custom modules for different configurations. For example, configB only cares about Cat.class schema.

    // Create my module A
    @RealmModule(classes = { Person.class, Dog.class })
    public class MyModule {
    }
    
    // Create the module B
    @RealmModule(classes = { Cat.class })
    public class MyOtherModule {
    }
    
    // Set the module in the RealmConfiguration to allow only classes defined by the module.
    RealmConfiguration configA = new RealmConfiguration.Builder()
      .modules(new MyModule())
      .name("A.realm")
      .build();
    
    RealmConfiguration configB = new RealmConfiguration.Builder()
      .modules(new MyOtherModule())
      .name("B.realm")
      .build();