utkbansal utkbansal - 5 months ago 44
Swift Question

RealmSwift - transaction completion

How do I know when a particular transaction has completed?

I want to run a particular block of code after a transaction is complete. How can I do this?

I am performing writes in the following war -

do {

try realm.write({
realm.add(<some object>)
})
}
catch {}

Answer

Best approach would be to write the method as an extension for Realm object.

extension Realm {

    /** Performs actions contained within the given block inside a write transaction with
    completion block.

     - parameter block: write transaction block
     - completion: completion executed after transaction block
    */
    func write(@noescape transactionBlock block: Void -> (), completion: Void -> ()) throws {
        do {
            try write(block)
            completion()
        } catch {
            throw error
        }
    }
}

Now you can use the extension just like a regular write(_:) method.

let realm = try! Realm()
let object = SomeObject()

try! realm.write(
        transactionBlock: {
            realm.add(object)
        },
        completion: {
            print("Write transaction finished")
    })