I am trying to understand how & when to use @AsyncOpen
wrapper with SwiftUI. Below are 2 ways I am opening a Synced Realm and both are working just fine.
Which of the 2 methods below is the correct way to open a Sync Realm?
Method 1 - passing flexibleSyncConfiguration()
via environment, then when calling @Environment(\.realm)
, realm will used passed config to open a Sync Realm
@main
struct Sample: SwiftUI.App {
@StateObject var app: RealmSwift.App = .init(id: "someId")
var body: some Scene {
WindowGroup {
if let user = app.currentUser {
ContentView()
.environment(\.realmConfiguration, getSyncRealmConfig(user: user))
.environmentObject(user)
} else {
LoginView(app: app)
}
}
}
private func getSyncRealmConfig(user: User) -> Realm.Configuration {
var config = user.flexibleSyncConfiguration { subs in
subs.append(QuerySubscription<Todo> { $0.ownerId == user.id })
}
config.schemaVersion = 1
config.objectTypes = [
Todo.self
]
return config
}
}
struct ContentView: View {
@Environment(\.realm) private var realm: Realm
@EnvironmentObject private var user: User
@ObservedResults(Todo) private var todos: Results<Todo>
var body: some View {
VStack {
Button("ADD") {
try! realm.write {
let todo = Todo(user: user)
realm.add(todo)
}
}
List(todos) { todo in
Text(todo._id.uuidString)
}
}
}
}
Method 2 - using @AsyncOpen/@AutoOpen
wrapper. Based on my understanding, @AsyncOpen
provides additional status on which stage the operation of opening sync is right now, however, you need to provide an “AppID” twice
@main
struct Sample: SwiftUI.App {
@StateObject var app: RealmSwift.App = .init(id: "someId")
var body: some Scene {
WindowGroup {
if let user = app.currentUser {
OpenSyncedRealm()
.environment(\.realmConfiguration, getSyncRealmConfig(user: user))
.environmentObject(user)
} else {
LoginView(app: app)
}
}
}
private func getSyncRealmConfig(user: User) -> Realm.Configuration {
var config = user.flexibleSyncConfiguration { subs in
subs.append(QuerySubscription<Todo> { $0.ownerId == user.id })
}
config.schemaVersion = 1
config.objectTypes = [
Todo.self
]
return config
}
}
struct OpenSyncedRealm: View {
@AsyncOpen(appId: "someId", timeout: 4000) var asyncOpen
var body: some View {
switch asyncOpen {
//...
case ..open(let realm):
// content view is the same
ContentView()
.environemnt(\.realm, realm)
// ...
}
}
}