在后台线程上查询领域并在 UI 线程上解析 ThreadSafeReference 有什么意义吗?

Is there any point in querying realm on a background thread and resolving a ThreadSafeReference on the UI thread?

似乎最近添加了 ThreadSafeReference 以帮助跨越线程边界。之前,根据我阅读的资料(可能并不详尽),建议只在您打算使用结果的线程上查询领域;在 UI 线程上有效地查询它。

在后台线程上查询 Realm 是否有好处,或者基本上 运行 再次解析 ThreadSafeReference 查询?

这里是使用 RxSwift 的一个例子:

import RxSwift
import RealmSwift 


public static func getAllMyModels() -> Observable<Results<MyModel>>{

    return Observable<ThreadSafeReference<Results<MyModel>>>.create{
        observer in

        // using this queue in this example only
        DispatchQueue.global(qos: .default).async {

            let realm = try! Realm()
            let models = realm.objects(MyModel.self)
            let safe = ThreadSafeReference(to: models)

            observer.onNext(safe)
            observer.onCompleted()
        }

        return Disposables.create()
    }
    .observeOn(MainScheduler.instance) // push us back to the UI thread to resolve the reference
    .map{
        safeValue in

        let realm = try! Realm()
        let value = realm.resolve(safeValue)!
        return value
    }
    .shareReplayLatestWhileConnected()
}

通过在某些后台线程上查询并在 UI 线程上解析,我是否有所收获?

好像没有必要。根据文档,查询已经在后台线程上完成,只要您附加了通知块:

Once the query has been executed, or a notification block has been added, the Results is kept up to date with changes made in the Realm, with the query execution performed on a background thread when possible. - https://realm.io/docs/swift/latest/#queries

ast 的指导是正确的,但我进一步挖掘并想 post 进一步确认他的回答。

kishikawa-katsumi,目前是 Realm 的软件工程师,在 Realm 的 public slack (https://realm-public.slack.com/archives/general/p1488960777001796) 中提供了对问题的回答:

For querying, it is fast enough in UI thread in most cases. If you're facing about a few slow complex queries, you can use background query. To execute queries in the background, use addNotificationBlock ().

notificationToken = realm
    .objects(...)
    .filter(...)
    .addNotificationBlock { (changes) in
        // The query is executed in background.
        // When the query is completed, then call this block
        ...
    }

Using addNotificationBlock(), the query is excuted in background, when the query is completed, then call the callback closure will be called. So ThreadSafeReference is rarely used in queries. ThreadSafeReference is used when you want to pass an object to another thread (for example, to specify it as a condition of a query or to use it as a parameter of an API request).

可以在此处找到有关从 GCD 线程(后台线程)订阅此块的其他信息,因为它需要运行循环。