【问题标题】:When should I call realm.close()?我应该什么时候调用 realm.close()?
【发布时间】:2016-11-14 11:21:21
【问题描述】:

我将 Realm 用于我的 React Native 应用程序。我正在让我的组件可以使用 Realm 实例,如官方example app 所示:

export default new Realm({schema: [Todo, TodoList]});.

当我随后用 Jest 进行测试时,我意识到只要我不打电话,这个过程就不会结束

afterAll(() => { realm.close(); });

在测试套件的末尾。

这让我思考是否以及何时应该在生产代码中调用realm.close()。不调用close有什么后果?如果推荐,关闭 Realm 实例的最佳方法是什么?

【问题讨论】:

    标签: react-native realm


    【解决方案1】:

    realm.close() 在您完成当前架构时使用。在 Realm api 页面中,它显示以下内容:

    close():关闭此 Realm,以便可以使用更新的模式版本重新打开它。调用此方法后,此 Realm 中的所有对象和集合都不再有效。

    如果您不想更改架构,则不必担心close 方法。

    完整参考:Realm close method

    【讨论】:

      【解决方案2】:

      一些好的,直截了当的参考:

      Realm 实例是引用计数的——如果你在一个线程中调用getInstance 两次,你也需要调用close 两次。这使您可以实现Runnable 类,而不必担心哪个线程将执行它们:只需以getInstance 开始它并以close 结束它。

      执行事务时(通常在后台线程中):

      1. 获取Realm 实例
      2. 用于executeTransaction
      3. 然后,马上close() 之后

      例如:

      Realm.getDefaultInstance()
      
          // use will close realm after the transaction is finished/failed
          .use { realm ->
      
              // DO NOT execute read/write operations outside of a transaction...
              // because it will lead to stale reads, exceptions, and other problems
      
              realm.executeTransaction { realm ->
                  // do things in the transaction (both reading & writing)
              }
          }
      

      在 main/UI/looper/handler 线程上,保持Realm 的实例打开,因为您通常有兴趣监听从该Realm 实例获得的RealmResults 的变化:强>

      1. Realm 实例在应用程序可见时创建/获取
      2. 该实例由在主线程上执行的所有操作(通常是读取操作)共享
      3. 应用程序关闭时,共享实例为close()d。

      例如:

      // in chronological order....on main UI thread
      
      // application starts....
      val realm = Realm.getDefaultInstance()
      
      // user navigating to some view...
      
      // execute a query that will return results that we're interested in displaying
      val realmResults = realm.where(Entity::class.java).findAllAsync()
      
      // need to hold a strong reference to the listener, otherwise it may stop 
      // receiving callbacks from Realm, because Realm only holds weak references to 
      // registered listeners
      val listener = RealmChangeListener<RealmResults<Entity>> { assessments ->
          // update UI
      }
      
      // add the listener to the query
      realmResults.addChangeListener(listener)
      
      // user shutting down app...close main thread's realm
      realm.close()
      

      【讨论】:

        猜你喜欢
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-11
        • 2021-09-07
        • 2013-03-11
        • 1970-01-01
        相关资源
        最近更新 更多