Search code examples
swiftrealmrx-swift

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


It appears that ThreadSafeReference was added recently to help move across thread boundaries. Prior, according to the sources I read (which were probably not exhaustive) the recommendation to was to just query realm on the thread you intend to use the results on; effectively query it on the UI thread.

Is there a benefit to querying Realm on a background thread or does resolving the ThreadSafeReference basically run the query again?

Using RxSwift here's an example of this:

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()
}

Did I gain anything by querying on some background thread and resolving on the UI thread?


Solution

  • Seems unnecessary. According to the docs, queries are already being done on a background thread, as long as you have attached a notification block:

    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