获取 Realm 实例(kotlin sdk,版本 0.10.0)的正确方法是什么? Java SDK 上 Realm.getDefaultInstance() 的替代方案?

问题描述 投票:0回答:2

我在我的应用程序类中初始化了领域,如下所示:

val realmConfig = RealmConfiguration.Builder(schema =
    setOf(User::class)
    )       .name("myrealm_DB.db")
            .schemaVersion(1)
            .deleteRealmIfMigrationNeeded()
            .log(LogLevel.ALL)
            .build()

    realm = Realm.open(configuration = realmConfig)

在另一个活动中获取领域实例的正确方法是什么?因为在 kotlin sdk 中我们没有 Realm.getDefaultInstance() 方法?有没有办法像全局 RealmManager 类一样创建?

android kotlin realm
2个回答
0
投票

不幸的是,由于它对于您在开发应用程序和企业模型时使用的每种模式和模型都非常具体,因此没有基本的答案。尽管如此,我还是会分享我在使用 Realm 时常用的一种模式。

object RealmProcessor {
  private var realmInstance: Realm? = nil
  fun startRealm(someSpecialProperties: <Type>, completion: () -> Unit? = {}){
    runInSafeQueue ({
      try {
        val config = RealmConfiguration.Builder(
          setOf(
            User::class,
            Message::class,
            MessageEmbed::class,
            MessageViewer::class,
            MessageRecipient::class,
            Inbox::class,
            InboxUser::class,
            Sync::class
          )
        )

        config.schemaVersion(1)
        config.deleteRealmIfMigrationNeeded()

        // We're using also Realm-JS, since we want the same directory that the JS thread created.
        config.name("my-percious-realm-$my_custom_property.realm")

        realmInstance = Realm.open(config.build())
      } catch(e: Error) {
        logError("Realm start error", thrown = e)
      }
    })
  }

  // Since the threads has to be same for write operations which we used for opening Realm making it singleton with one dispatcher.
  private fun runInSafeQueue(runner: suspend () -> Unit?, didCatch: (Error) -> Unit = { _ -> }) {
    GlobalScope.launch {
      try {
        runner()
      } catch (e: Error) {
        didCatch(e)
      }
    }
  }

  // This is very basic example with making this Object class a generic Realm accessor so you initialize it in very first activity that your app used you can easily keep accessing it from any activity
  inline fun <reified T: BaseRealmObject>getFromRealm(id: Int): RealmResults<T>? {
    return realmInstance?.query(T::class, "id == $0", id)?.find()
  }

  fun <T: RealmObject>createInRealm(objectToCopyRealm: T) {
    runInSafeQueue({
      realmInstance?.write {
        copyToRealm(objectToCopyRealm)
        null
      }
    })
  }

  fun changeUserValue(changedValue: Int) {
    runInSafeQueue({
      realmInstance?.write {
        val objectToChange = getFromRealm<User>(20)
        objectToChange?.first()?.personalMessageRoom = changedValue
      }
    })
  }
}

希望可以帮助任何正在寻找起点的人


0
投票

您可以创建一个单例来保存配置并获取领域实例。

import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration

class RealmDB {
    companion object {
        private var instance: Realm? = null

        fun getInstance(): Realm {
            if (instance == null) {
                val config = RealmConfiguration.create(schema = setOf(AvariaRealmObject::class))
                val realm: Realm = Realm.open(config)
                instance = realm
            }
            return instance!!
        }
    }
}

并使用如下:

      val realm = RealmDB.getInstance()

        realm.writeBlocking {
            copyToRealm(RealmObject().apply {
                ....
            })
        } 
© www.soinside.com 2019 - 2024. All rights reserved.