Nero
Nero

Reputation: 51

Is realm.write asynchronous

I am trying to add CustomUserData to my MongoDB Realm Database and then refresh the user data.

But as it seems is realm.write asynchronous, whereas I thought it would be synchronous (Swift Realm Write method is Sync or Async Thread). So my question is what's really the case and when its synchronous why does the .refreshCustomData() function is only able to fetch the new data after a short delay.

try! realm.write {
   realm.add(member)
}

app.currentUser!.refreshCustomData()
// -> after the refresh the customUserData is still empty
// only if you call it with a short delay the result contains the new written data

Upvotes: 1

Views: 2564

Answers (1)

mcscxv
mcscxv

Reputation: 134

No, it is not asynchronous. Have a look at the implementation (removed everything that is not important to understand). A write transaction is simply started and committed if no exception has occurred, otherwise the transaction is rolled back.

public func write<Result>(_ block: (() throws -> Result)) throws -> Result {
    beginWrite()
    var ret: Result!
    do {
        ret = try block()
    } catch let error {
        if isInWriteTransaction { cancelWrite() }
        throw error
    }
    if isInWriteTransaction { try commitWrite(withoutNotifying: tokens) }
    return ret
}

But: If you query the data just written in another thread, that is another story. New objects just wont be visible on another thread for some time.

My solutions to this is: stay on the same thread for write and read operations.

See also: Saving data and query it in different threads with Realm

Upvotes: 2

Related Questions