# Open Synced Realms in SwiftUI using @Auto/AsyncOpen

## Introduction

We’re very happy to announce that v10.12.0 of the Realm Cocoa SDK includes our two new property wrappers `@AutoOpen` and `@AsyncOpen` for asynchronous opening of a realm for Realm Sync users. This new feature, which is a response to your community feedback, aligns with our goal to make our developer experience better and more effortless, integrating it with SwiftUI, and removing boilerplate code.

Up until now, the standard approach for opening a realm for any sync user is to call `Realm.asyncOpen()` using a user’s sync configuration, then publish the opened Realm to the view:

``` swift
enum AsyncOpenState {
    case waiting
    case inProgress(Progress)
    case open(Realm)
    case error(Error)
}

struct AsyncView: View {
    @State var asyncOpenState: AsyncOpenState = .waiting

    var body: some View {
        switch asyncOpenState {
        case .waiting:
            ProgressView()
                .onAppear(perform: initAsyncOpen)
        case .inProgress(let progress):
            ProgressView(progress)
        case .open(let realm):
            ContactsListView()
                .environment(\.realm, realm)
        case .error(let error):
            ErrorView(error: error)
        }
    }

    func initAsyncOpen() {
        let app = App(id: "appId")
        guard let currentUser = app.currentUser else { return }
        let realmConfig = currentUser.configuration(partitionValue: "myPartition")
        Realm.asyncOpen(configuration: realmConfig,
                        callbackQueue: DispatchQueue.main) { result in
            switch result {
            case .success(let realm):
                asyncOpenState = .open(realm)
            case .failure(let error):
                asyncOpenState = .error(error)
            }
        }.addProgressNotification { syncProgress in
            let progress = Progress(totalUnitCount: Int64(syncProgress.transferredBytes))
            progress.completedUnitCount = Int64(syncProgress.transferredBytes)
            asyncOpenState = .inProgress(progress)
        }
    }
}
```

With `@AsyncOpen` and `@AutoOpen`, we are reducing development time and boilerplate, making it easier, faster, and cleaner to implement Realm.asyncOpen(). `@AsyncOpen` and `@AutoOpen` give the user the possibility to cover two common use cases in synced apps.

> **Build better mobile apps with Atlas Device Sync**: Atlas Device Sync is a fully-managed mobile backend-as-a-service. Leverage out-of-the-box infrastructure, data synchronization capabilities, built-in network handling, and much more to quickly launch enterprise-grade mobile apps. Get started now by build: Deploy Sample for Free!

## Prerequisites

- Realm Cocoa 10.12.0+

## @AsyncOpen

With the `@AsyncOpen` property wrapper, we have the same behavior as using `Realm.asyncOpen()`, but with a much more natural API for SwiftUI developers. Using this property wrapper prevents your app from trying to fetch the Realm file if there is no network connection, and it will only return a realm when it's synced with MongoDB Realm data. If there is no internet connection, then @AsyncOpen< will throw an error.

Let’s take, for example, a game app, which the user can play both on an iPhone and iPad. Having the data not updated would result in losing track of the current status of the player. In this case, it’s very important to have our data updated with any latest changes. This is the perfect use case for `@AsyncOpen`. 

This property wrapper's API gives you the flexibility to optionally specify a MongoDB Realm AppId. If no AppId is provided, and you’ve only used one ID within your App, then that will be used. You can also provide a timeout for your asynchronous operation:

```swift
@AsyncOpen(appId: "appId",
            partitionValue: "myPartition",
            configuration: Realm.Configuration(objectTypes: SwiftPerson.self])
            timeout: 20000)
var asyncOpen
```

Adding it to your SwiftUI App is as simple as declaring it in your view and have your view react to the state of the sync operation:

- Display a progress view while downloading or waiting for a user to be logged in.
- Display an error view if there is a failure during sync.
- Navigate to a new view after our realm is opened

Once the synced realm has been successfully opened, you can pass it to another view (embedded or via a navigation link):

```swift
struct AsyncOpenView: View {
    @AsyncOpen(appId: "appId",
               partitionValue: "myPartition",
               configuration: Realm.Configuration(objectTypes: [SwiftPerson.self])
               timeout: 20000)
    var asyncOpen

    var body: some View {
        VStack {
            switch asyncOpen {
            case .connecting:
                ProgressView()
            case .waitingForUser:
                ProgressView("Waiting for user to logged in...")
            case .open(let realm):
                ListView()
                    .environment(\.realm, realm)
            case .error(let error):
                ErrorView(error: error)
            case .progress(let progress):
                ProgressView(progress)
            }
        }
    }
}
```

If you have been using Realm.asyncOpen() in your current SwiftUI App and want to maintain the same behavior, you may want to migrate to  `@AsyncOpen`. It will simplify your code and make it more intuitive.

## @AutoOpen

`@AutoOpen` should be used when you want to work with the synced realm file even when there is no internet connection.

Let’s take, for example, Apple’s Notes app, which tries to sync your data if there is internet access and shows you all the notes synced from other devices. If there is no internet connection, then Notes shows you your local (possibly stale) data. This use case is perfect for the `@AutoOpen` property wrapper. When the user recovers a network connection, Realm will sync changes in the background, without the need to add any extra code.

The syntax for using `@AutoOpen` is the same as for `@AsyncOpen`:

```swift
struct AutoOpenView: View {
    @AutoOpen(appId: "appId",
              partitionValue: "myPartition",
              configuration: Realm.Configuration(objectTypes: [SwiftPerson.self])
              timeout: 10000)
    var autoOpen

    var body: some View {
        VStack {
            switch autoOpen {
            case .connecting:
                ProgressView()
            case .waitingForUser:
                ProgressView("Waiting for user to logged in...")
            case .open(let realm):
                ContactView()
                    .environment(\.realm, realm)
            case .error(let error):
                ErrorView(error: error)
            case .progress(let progress):
                ProgressView(progress)
            }
        }
    }
}
```

## One Last Thing… 

We added a new key to our set of Environment Values: a “partition value” environment key which is used by our new property wrappers `@AsyncOpen` and `@AutoOpen` to dynamically inject a partition value when it's derived and not static. For example, in the case of using the user id as a partition value, you can pass this environment value to the view where `@AsyncOpen` or `@AutoOpen` are used:

```swift
AsyncView()
    .environment(\.partitionValue, user.id!)
```

## Conclusion

With these property wrappers, we continue to better integrate Realm into your SwiftUI apps. With the release of this feature, and more to come, we want to make it easier for you to incorporate our SDK and sync functionality into your apps, no matter whether you’re using UIKit or SwiftUI.

We are excited for our users to test these new features. Please share any feedback or ideas for new features in our [community forum.

Documentation on both of these property wrappers can be found in our docs.