What is the recommended way to use threads with RealmSwift?


#1

Greetings,

Can anyone share with me the recommended way of fetching and saving realm objects with threads following mvvm principle and decoupling?

Here is how I tried to do it:

public func realmAsync(block: @escaping ((Realm) -> Void)) {
    let backgroundQueue = DispatchQueue(label: ".mementos", qos: .background)
    backgroundQueue.async {
        autoreleasepool {
            do {
                let realm = try Realm()
                try realm.write {
                    block(realm)
                }
            } catch {
                print("Realm Error \(error)")
            }

        }
    }
}

then I do this

    func getLiveUser(completion: @escaping (Observable<User>) -> Void) {
        realmAsync { (Realm) in
            let user = Realm.objects(User.self).first
            completion(Observable.from(object: user ?? User()))
        }
    }