Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Writing Sync Data on main thread

I may be overlooking something in the Sync Data getting started guide but it says

Therefore, it’s a best practice never to write on the main thread when using Realm Sync.

but then the example code writes data on the main thread.

// Write to the realm. No special syntax required for synced realms.
try! realm.write {
  realm.add(Task(partition: partitionValue, name: "My task"))
}

and indicates there’s no special syntax required even though it’s not supposed to be done that way.

Is there clarification on that and perhaps some best practice code?

Also, previously with realm when writing large amounts of data the write would be wrapped in an autorelease pool - is that still the case?

@Jay Yes there is a tradeoff between creating a Tutorial app that shows the bare minimum of code and then a best practices app that contains all the recommended best practices. For instance, every write should likely be wrapped in do/try/catch block but we don’t put that in the Tasks app because it would make the code verbose and we assume that every mobile developer should be following standard mobile development best practices - this is not specific to realm but is a best practice for any mutation to the data layer.

You can find a sample on SO - you should use an autoReleasePool, open a realm, make a write, and then make sure to close the realm by setting the realm variable to null when you are done with the write.

@Ian_Ward

Thanks for the clarification.

Since MongoDB Realm is a different product than Realm in many ways and the Realm Documentation specifically calls for the use of autorelease pools as well as how to handle threads when syncing, I thought it best to ask than to assume.

I understand why you would simplify the first steps tutorial, but it’s still not clear to me how to architecture an iOS app correctly for MongoDB Realm sync (given that writes on the main thread are a no-no).

A demo project (like Tasks, but demonstrating best practices) would be very helpful.

1 Like