领域:在应用中使用一个或多个领域(以及一个或多个架构)

2022-09-03 02:34:50

我正在实现一个应用程序,它使用 Realm 在某些点(它们之间不相关)保留数据。例如:

  1. 保存用户收藏的项目。
  2. (应用程序有聊天)保存聊天对话和最近常量
  3. 为应用的某些请求实现持久缓存
  4. 保存最近的搜索/表单以提供自动完成

(让我们将每个点命名为模块/包)

每个模块/包都有一些要保留的模块/包。我应该如何组织它?从代码清洁度,性能或任何我应该关心的角度来看RealmObjects

选项 A:使用具有唯一架构的唯一(默认)领域:

Realm.getInstance(context)

访问每个模块/包中的正确内容RealmObjects

选项 B:将多个领域与默认模式结合使用

在每个模块中使用的领域中指定不同的名称(使用默认模式)。RealmConfiguration

由于数据属于应用的不同部分,隔离且不互连,因此对每个模块使用不同的领域名称。

选项 C:使用多个领域,并确定与每个应用程序包的模式一起使用的模型类的作用域为每个独立包指定名称和架构。例如:

public static Realm getChat(Context context){
    RealmConfiguration config = new RealmConfiguration.Builder(context)
            .name("chat.realm")
            .schemaVersion(1)
            .setModules(new ChatRealmModule())
            .build();
    return Realm.getInstance(config);
}

// Create the module
@RealmModule(classes = { ChatRoom.class, ChatMessage.class, ChatUser.class})
public static class ChatRealmModule{
}

选项D:其他?


答案 1

如果你的数据真的完全断开了,我会选择选项C)它可以进行彻底的分离。迁移更容易处理,而且性能提升也非常小,因为 Realm 必须不时地遍历 Realm 中的所有模型类。

但没有一个选项是“错误的”。


答案 2

是的,你可以,尽管你通常可以在 Realm 上有多个类

配置其他铰链显示了如何指定不同的文件路径,例如:

RealmConfiguration myConfig = new RealmConfiguration.Builder(context)
  .name("myrealm.realm")
  .schemaVersion(2)
  .modules(new MyCustomSchema())
  .build();

RealmConfiguration otherConfig = new RealmConfiguration.Builder(context)
  .name("otherrealm.realm")
  .schemaVersion(5)
  .modules(new MyOtherSchema())
  .build();

Realm myRealm = Realm.getInstance(myConfig);
Realm otherRealm = Realm.getInstance(otherConfig);

@RealmModule(classes={Abc.class, Pqrs.class, Xyz.class})
class MyCustomSchema{}

@RealmModule(classes={Abc1.class, Pqrs2.class, Xyz2.class})
class MyOtherSchema{}

推荐