使用 Realm 保存数据并在不同线程中查询 [英] Saving data and query it in different threads with Realm

查看:34
本文介绍了使用 Realm 保存数据并在不同线程中查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Realm 时遇到线程问题(我使用的是 3.7 版).

I'm experiencing threading issues with Realm (I'm using version 3.7).

如果我在thread A中保存了一些数据,一秒钟后,我在thread B中查询相同的数据,有时会导致thread B 不会使用 thread A 中保存的一秒前的最新数据进行更新.

If I save some data in thread A, and one second after, I query the same data in thread B, sometimes results in thread B are not updated with the latest data saved one second before in thread A.

我想知道这是否正常,或者有没有办法减轻它.

I would like to know if is normal, or there is a way to mitigate it.

推荐答案

给定线程上的开放领域保留了底层数据库的版本化视图.如果线程与 Looper 相关联,这可以自动更新.

An open Realm on a given thread retains a versioned view of the underlying database. This can be updated automatically if the thread is associated with a Looper.

在普通后台线程的情况下,它没有looper,因此在以下情况下更新:

In case of a normal background thread, it does not have a looper, so it is updated if:

  • 该线程上的所有 Realm 实例都已关闭,稍后再打开

  • all Realm instances on that thread are closed, then opened later

一个交易被打开

refresh() 被调用(注意,如果在循环线程上调用,这会立即评估异步查询)

refresh() is called (note, if called on looper thread, this makes async queries be evaluated immediately)

如果您不为每个 getInstance() 调用调用 .close(),则很可能最终得到过时的数据.

You most likely end up with outdated data if you don't call .close() for each getInstance() call.

这篇关于使用 Realm 保存数据并在不同线程中查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆