Best way to manage realm instance?

Hi. I have a question for managing realm instance.

I use old version and I always make realm instance eveny CRUD

func writeSomthing() {
  let realm = try Realm()
  try realm.write {
     // create or update
  }
}
func readSomething() -> SomeObject {
  let realm = try Realm()
  return try realm.object(SomeObject.self)
}

Recently, I consider to update RealmSwift SDK latest version.
I think document says use single instance.

class SomeViewModel {
 private let realm: Realm

func writeSomthing() {
  try self.realm.write {
     // create or update
  }
}
func readSomething() -> SomeObject {
  return try self.realm.object(SomeObject.self)
 }
}
`
So I want to know best way to manage realm instance.
Please give me your insights.
Thank you.

This is a great question and I feel the documentation should really include some Best Practices on this topic.

The answer is: it depends on your use case.

If you are not using async/awaits, sync’ing or tasks that use threading, the first option works perfectly and is recommended (and could work even if you are)

When you use sync’ing, actor isolation (threading) a singleton is likely a better way of going IMO.

For us - even when apps are simple, we still use a singleton to return the Realm as we have some configuration options that need to be set when opening a Realm and the singleton requires far less code to get the realm

if let maybeRealm = MySingletonRealm() {
   //do some Realm read and writes
}

Hope that helps.

1 Like

Thank you for reply!
I will discuss my colleagues with your reply!