# Building a Mobile Chat App Using Realm – The New and Easier Way

In my last post, I walked through how to integrate Realm into a mobile chat app in Building a Mobile Chat App Using Realm – Integrating Realm into Your App. Since then, the Realm engineering team has been busy, and Realm-Swift 10.6 introduced new features that make the SDK way more "SwiftUI-native." For developers, that makes integrating Realm into SwiftUI views much simpler and more robust. This article steps through building the same chat app using these new features. Everything in Building a Mobile Chat App Using Realm – Integrating Realm into Your App still works, and it's the best starting point if you're building an app with UIKit rather than SwiftUI.

Both of these articles follow-up on Building a Mobile Chat App Using Realm – Data Architecture. Read that post first if you want to understand the Realm data/partitioning architecture and the decisions behind it.

This article targets developers looking to build the Realm mobile database into their SwiftUI mobile apps and use MongoDB Atlas Device Sync.

If you've already read Building a Mobile Chat App Using Realm – Integrating Realm into Your App, then you'll find some parts unchanged here. As an example, there are no changes to the backend Realm application. I'll label those sections with "Unchanged" so that you know it's safe to skip over them.

RChat is a chat application. Members of a chat room share messages, photos, location, and presence information with each other. This version is an iOS (Swift and SwiftUI) app, but we will use the same data model and backend Realm application to build an Android version in the future.

If you're looking to add a chat feature to your mobile app, you can repurpose the article's code and the associated repo. If not, treat it as a case study that explains the reasoning behind the data model and partitioning/syncing decisions taken. You'll likely need to make similar design choices in your apps.

>
>
>Watch this demo of the app in action.
>
>:youtube]{vid=BlV9El_MJqk}
>
>

>
>
>This article was updated in July 2021 to replace `objc` and `dynamic` with the `@Persisted` annotation that was introduced in Realm-Cocoa 10.10.0.
>
>

## Prerequisites

If you want to build and run the app for yourself, this is what you'll need:

-   iOS14.2+
-   XCode 12.3+
-   Realm-Swift 10.6+ (recommended to use the Swift Package Manager (SPM) rather than Cocoa Pods)
-   [MongoDB Atlas account and a (free) Atlas cluster

## Walkthrough

The iOS app uses MongoDB Atlas Device Sync to share data between instances of the app (e.g., the messages sent between users). This walkthrough covers both the iOS code and the backend Realm app needed to make it work. Remember that all of the code for the final app is available in the GitHub repo.

### Create a Backend Atlas App (Unchanged)

From the Atlas UI, select the "App Services" tab (formerly "Realm").  Select the options to indicate that you're creating a new iOS mobile app and then click "Start a New App".

Name the app "RChat" and click "Create Application".

Copy the "App ID." You'll need to use this in your iOS app code:

### Connect iOS App to Your App (Unchanged)

The SwiftUI entry point for the app is RChatApp.swift. This is where you define your link to your Realm application (named `app`) using the App ID from your new backend Atlas App Services app:

``` swift
import SwiftUI
import RealmSwift
let app = RealmSwift.App(id: "rchat-xxxxx") // TODO: Set the Realm application ID
@main
struct RChatApp: SwiftUI.App {
   @StateObject var state = AppState()

   var body: some Scene {
      WindowGroup {
            ContentView()
               .environmentObject(state)
      }
   }
}
```

Note that we created an instance of AppState and pass it into our top-level view (ContentView) as an `environmentObject`. This is a common SwiftUI pattern for making state information available to every view without the need to explicitly pass it down every level of the view hierarchy:

``` swift
import SwiftUI
import RealmSwift
let app = RealmSwift.App(id: "rchat-xxxxx") // TODO: Set the Realm application ID
@main
struct RChatApp: SwiftUI.App {
   @StateObject var state = AppState()
   var body: some Scene {
      WindowGroup {
            ContentView()
               .environmentObject(state)
      }
   }
}
```

### Realm Model Objects

These are largely as described in Building a Mobile Chat App Using Realm – Data Architecture.  I'll highlight some of the key changes using the User Object class as an example:

``` swift
import Foundation
import RealmSwift

class User: Object, ObjectKeyIdentifiable {
   @Persisted var _id = UUID().uuidString
   @Persisted var partition = "" // "user=_id"
   @Persisted var userName = ""
   @Persisted var userPreferences: UserPreferences?
   @Persisted var lastSeenAt: Date?
   @Persisted var conversations = List()
   @Persisted var presence = "Off-Line"

   override static func primaryKey() -> String? {
      return "_id"
   }
}
```

`User` now conforms to Realm-Cocoa's `ObjectKeyIdentifiable` protocol, automatically adding identifiers to each instance that are used by SwiftUI (e.g., when iterating over results in a `ForEach` loop). It's like `Identifiable` but integrated into Realm to handle events such as Atlas Device Sync adding a new object to a result set or list.

`conversations` is now a `var` rather than a `let`, allowing us to append new items to the list.

### Application-Wide State: AppState

The `AppState` class is so much simpler now. Wherever possible, the opening of a Realm is now handled when opening the view that needs it.

Views can pass state up and down the hierarchy. However, it can simplify state management by making some state available application-wide. In this app, we centralize this app-wide state data storage and control in an instance of the AppState class.

A lot is going on in `AppState.swift`, and you can view the full file in the repo.

As part of adopting the latest Realm-Cocoa SDK feature, I no longer need to store open Realms in `AppState` (as Realms are now opened as part of loading the view that needs them). `AppState` contains the `user` attribute to represent the user currently logged into the app (and Realm). If `user` is set to `nil`, then no user is logged in:

``` swift
class AppState: ObservableObject {
   ...
   var user: User?
   ...
}
```

The app uses the Realm SDK to interact with the back end Atlas App Services application to perform actions such as logging into Realm. Those operations can take some time as they involve accessing resources over the internet, and so we don't want the app to sit busy-waiting for a response. Instead, we use Combine publishers and subscribers to handle these events. `loginPublisher`, `logoutPublisher`, and `userRealmPublisher` are publishers to handle logging in, logging out, and opening Realms for a user:

``` swift
class AppState: ObservableObject {
   ...
   let loginPublisher = PassthroughSubject()
   let logoutPublisher = PassthroughSubject()
   let userRealmPublisher = PassthroughSubject()
   ...
}
```

When an `AppState` class is instantiated, the actions are assigned to each of the Combine publishers:

``` swift
init() {
   _  = app.currentUser?.logOut()
   initLoginPublisher()
   initUserRealmPublisher()
   initLogoutPublisher()
}
```

We'll later see that an event is sent to `loginPublisher` when a user has successfully logged in. In `AppState`, we define what should be done when those events are received. Events received on `loginPublisher` trigger the opening of a realm with the partition set to `user=`, which in turn sends an event to `userRealmPublisher`:

``` swift
func initLoginPublisher() {
loginPublisher
   .receive(on: DispatchQueue.main)
   .flatMap { user -> RealmPublishers.AsyncOpenPublisher in
         self.shouldIndicateActivity = true
         let realmConfig = user.configuration(partitionValue: "user=\(user.id)")
         return Realm.asyncOpen(configuration: realmConfig)
   }
   .receive(on: DispatchQueue.main)
   .map {
         return $0
   }
   .subscribe(userRealmPublisher)
   .store(in: &self.cancellables)
}
```

When the Realm has been opened and the Realm sent to `userRealmPublisher`, `user` is initialized with the `User` object retrieved from the Realm. The user's presence is set to `onLine`:

``` swift
func initUserRealmPublisher() {
   userRealmPublisher
      .sink(receiveCompletion: { result in
            if case let .failure(error) = result {
               self.error = "Failed to log in and open user realm: \(error.localizedDescription)"
            }
      }, receiveValue: { realm in
            print("User Realm User file location: \(realm.configuration.fileURL!.path)")
            self.userRealm = realm
            self.user = realm.objects(User.self).first
            do {
               try realm.write {
                  self.user?.presenceState = .onLine
               }
            } catch {
               self.error = "Unable to open Realm write transaction"
            }
            self.shouldIndicateActivity = false
      })
      .store(in: &cancellables)
}
```

After logging out of Realm, we simply set `user` to nil:

``` swift
func initLogoutPublisher() {
  logoutPublisher
      .receive(on: DispatchQueue.main)
      .sink(receiveCompletion: { _ in
      }, receiveValue: { _ in
         self.user = nil
      })
      .store(in: &cancellables)
}
```

### Enabling Email/Password Authentication in the Atlas App Services App (Unchanged)

After seeing what happens **after** a user has logged into Realm, we need to circle back and enable email/password authentication in the backend Atlas App Services app. Fortunately, it's straightforward to do.

From the Atlas UI, select "Authentication" from the lefthand menu, followed by "Authentication Providers." Click the "Edit" button for "Email/Password":

    

Enable the provider and select "Automatically confirm users" and "Run a password reset function." Select "New function" and save without making any edits:

    

Don't forget to click on "REVIEW & DEPLOY" whenever you've made a change to the backend Realm app.

### Create `User` Document on User Registration (Unchanged)

When a new user registers, we need to create a `User` document in Atlas that will eventually synchronize with a `User` object in the iOS app. Atlas provides authentication triggers that can automate this.

Select "Triggers" and then click on "Add a Trigger":

    

Set the "Trigger Type" to "Authentication," provide a name, set the "Action Type" to "Create" (user registration), set the "Event Type" to "Function," and then select "New Function":

    

Name the function `createNewUserDocument` and add the code for the function:

``` javascript
exports = function({user}) {
   const db = context.services.get("mongodb-atlas").db("RChat");
   const userCollection = db.collection("User");
   const partition = `user=${user.id}`;
   const defaultLocation = context.values.get("defaultLocation");
   const userPreferences = {
      displayName: ""
   };
   const userDoc = {
      _id: user.id,
      partition: partition,
      userName: user.data.email,
      userPreferences: userPreferences,
      location: context.values.get("defaultLocation"),
      lastSeenAt: null,
      presence:"Off-Line",
      conversations: ]
   };
   return userCollection.insertOne(userDoc)
   .then(result => {
      console.log(`Added User document with _id: ${result.insertedId}`);
   }, error => {
      console.log(`Failed to insert User document: ${error}`);
   });
};
```

Note that we set the `partition` to `user=`, which matches the partition used when the iOS app opens the User Realm.

"Save" then "REVIEW & DEPLOY."

### Define Schema (Unchanged)

Refer to [Building a Mobile Chat App Using Realm – Data Architecture to better understand the app's schema and partitioning rules. This article skips the analysis phase and just configures the schema.

Browse to the "Rules" section in the App Services UI and click on "Add Collection." Set "Database Name" to `RChat` and "Collection Name" to `User`. We won't be accessing the `User` collection directly through App Services, so don't select a "Permissions Template." Click "Add Collection":

    

At this point, I'll stop reminding you to click "REVIEW & DEPLOY!"

Select "Schema," paste in this schema, and then click "SAVE":

``` javascript
{
"bsonType": "object",
"properties": {
   "_id": {
      "bsonType": "string"
   },
   "conversations": {
      "bsonType": "array",
      "items": {
      "bsonType": "object",
      "properties": {
         "displayName": {
            "bsonType": "string"
         },
         "id": {
            "bsonType": "string"
         },
         "members": {
            "bsonType": "array",
            "items": {
            "bsonType": "object",
            "properties": {
               "membershipStatus": {
                  "bsonType": "string"
               },
               "userName": {
                  "bsonType": "string"
               }
            },
            "required": 
               "membershipStatus",
               "userName"
            ],
            "title": "Member"
            }
         },
         "unreadCount": {
            "bsonType": "long"
         }
      },
      "required": [
         "unreadCount",
         "id",
         "displayName"
      ],
      "title": "Conversation"
      }
   },
   "lastSeenAt": {
      "bsonType": "date"
   },
   "partition": {
      "bsonType": "string"
   },
   "presence": {
      "bsonType": "string"
   },
   "userName": {
      "bsonType": "string"
   },
   "userPreferences": {
      "bsonType": "object",
      "properties": {
      "avatarImage": {
         "bsonType": "object",
         "properties": {
            "_id": {
            "bsonType": "string"
            },
            "date": {
            "bsonType": "date"
            },
            "picture": {
            "bsonType": "binData"
            },
            "thumbNail": {
            "bsonType": "binData"
            }
         },
         "required": [
            "_id",
            "date"
         ],
         "title": "Photo"
      },
      "displayName": {
         "bsonType": "string"
      }
      },
      "required": [],
      "title": "UserPreferences"
   }
},
"required": [
   "_id",
   "partition",
   "userName",
   "presence"
],
"title": "User"
}
```

    

Repeat for the `Chatster` schema:

``` javascript
{
"bsonType": "object",
"properties": {
   "_id": {
      "bsonType": "string"
   },
   "avatarImage": {
      "bsonType": "object",
      "properties": {
      "_id": {
         "bsonType": "string"
      },
      "date": {
         "bsonType": "date"
      },
      "picture": {
         "bsonType": "binData"
      },
      "thumbNail": {
         "bsonType": "binData"
      }
      },
      "required": [
      "_id",
      "date"
      ],
      "title": "Photo"
   },
   "displayName": {
      "bsonType": "string"
   },
   "lastSeenAt": {
      "bsonType": "date"
   },
   "partition": {
      "bsonType": "string"
   },
   "presence": {
      "bsonType": "string"
   },
   "userName": {
      "bsonType": "string"
   }
},
"required": [
   "_id",
   "partition",
   "presence",
   "userName"
],
"title": "Chatster"
}
```

And for the `ChatMessage` collection:

``` javascript
{
"bsonType": "object",
"properties": {
   "_id": {
      "bsonType": "string"
   },
   "author": {
      "bsonType": "string"
   },
   "image": {
      "bsonType": "object",
      "properties": {
      "_id": {
         "bsonType": "string"
      },
      "date": {
         "bsonType": "date"
      },
      "picture": {
         "bsonType": "binData"
      },
      "thumbNail": {
         "bsonType": "binData"
      }
      },
      "required": [
      "_id",
      "date"
      ],
      "title": "Photo"
   },
   "location": {
      "bsonType": "array",
      "items": {
      "bsonType": "double"
      }
   },
   "partition": {
      "bsonType": "string"
   },
   "text": {
      "bsonType": "string"
   },
   "timestamp": {
      "bsonType": "date"
   }
},
"required": [
   "_id",
   "partition",
   "text",
   "timestamp"
],
"title": "ChatMessage"
}
```

### Enable Atlas Device Sync (Unchanged)

We use Atlas Device Sync to synchronize objects between instances of the iOS app (and we'll extend this app also to include Android). It also syncs those objects with Atlas collections. Note that there are three options to create a schema:

1.  Manually code the schema as a JSON schema document.
2.  Derive the schema from existing data stored in Atlas. (We don't yet have any data and so this isn't an option here.)
3.  Derive the schema from the Realm objects used in the mobile app.

We've already specified the schema and so will stick to the first option.

Select "Sync" and then select your Atlas cluster. Set the "Partition Key" to the `partition` attribute (it appears in the list as it's already in the schema for all three collections), and the rules for whether a user can sync with a given partition:

    

The "Read" rule controls whether a user can establish a one-way read-only sync relationship to the mobile app for a given user and partition. In this case, the rule delegates this to an Atlas Function named `canReadPartition`:

``` json
{
   "%%true": {
      "%function": {
         "arguments": [
         "%%partition"
         ],
         "name": "canReadPartition"
      }
   }
}
```

The "Write" rule delegates to the `canWritePartition`:

``` json
{
   "%%true": {
      "%function": {
         "arguments": [
         "%%partition"
         ],
         "name": "canWritePartition"
      }
   }
}
```

Once more, we've already seen those functions in [Building a Mobile Chat App Using Realm – Data Architecture but I'll include the code here for completeness.

canReadPartition:

``` javascript
exports = function(partition) {
   console.log(`Checking if can sync a read for partition = ${partition}`);
   const db = context.services.get("mongodb-atlas").db("RChat");
   const chatsterCollection = db.collection("Chatster");
   const userCollection = db.collection("User");
   const chatCollection = db.collection("ChatMessage");
   const user = context.user;
   let partitionKey = "";
   let partitionVale = "";
   const splitPartition = partition.split("=");
   if (splitPartition.length == 2) {
      partitionKey = splitPartition0];
      partitionValue = splitPartition[1];
      console.log(`Partition key = ${partitionKey}; partition value = ${partitionValue}`);
   } else {
      console.log(`Couldn't extract the partition key/value from ${partition}`);
      return false;
   }
   switch (partitionKey) {
   case "user":
      console.log(`Checking if partitionValue(${partitionValue}) matches user.id(${user.id}) – ${partitionKey === user.id}`);
      return partitionValue === user.id;
   case "conversation":
      console.log(`Looking up User document for _id = ${user.id}`);
      return userCollection.findOne({ _id: user.id })
      .then (userDoc => {
      if (userDoc.conversations) {
         let foundMatch = false;
         userDoc.conversations.forEach( conversation => {
            console.log(`Checking if conversaion.id (${conversation.id}) === ${partitionValue}`)
            if (conversation.id === partitionValue) {
            console.log(`Found matching conversation element for id = ${partitionValue}`);
            foundMatch = true;
            }
         });
         if (foundMatch) {
            console.log(`Found Match`);
            return true;
         } else {
            console.log(`Checked all of the user's conversations but found none with id == ${partitionValue}`);
            return false;
         }
      } else {
         console.log(`No conversations attribute in User doc`);
         return false;
      }
      }, error => {
      console.log(`Unable to read User document: ${error}`);
      return false;
      });
   case "all-users":
      console.log(`Any user can read all-users partitions`);
      return true;
   default:
      console.log(`Unexpected partition key: ${partitionKey}`);
      return false;
   }
};
```

[canWritePartition:

``` javascript
exports = function(partition) {
console.log(`Checking if can sync a write for partition = ${partition}`);
const db = context.services.get("mongodb-atlas").db("RChat");
const chatsterCollection = db.collection("Chatster");
const userCollection = db.collection("User");
const chatCollection = db.collection("ChatMessage");
const user = context.user;
let partitionKey = "";
let partitionVale = "";
const splitPartition = partition.split("=");
if (splitPartition.length == 2) {
   partitionKey = splitPartition0];
   partitionValue = splitPartition[1];
   console.log(`Partition key = ${partitionKey}; partition value = ${partitionValue}`);
} else {
   console.log(`Couldn't extract the partition key/value from ${partition}`);
   return false;
}
   switch (partitionKey) {
   case "user":
      console.log(`Checking if partitionKey(${partitionValue}) matches user.id(${user.id}) – ${partitionKey === user.id}`);
      return partitionValue === user.id;
   case "conversation":
      console.log(`Looking up User document for _id = ${user.id}`);
      return userCollection.findOne({ _id: user.id })
      .then (userDoc => {
      if (userDoc.conversations) {
         let foundMatch = false;
         userDoc.conversations.forEach( conversation => {
            console.log(`Checking if conversaion.id (${conversation.id}) === ${partitionValue}`)
            if (conversation.id === partitionValue) {
            console.log(`Found matching conversation element for id = ${partitionValue}`);
            foundMatch = true;
            }
         });
         if (foundMatch) {
            console.log(`Found Match`);
            return true;
         } else {
            console.log(`Checked all of the user's conversations but found none with id == ${partitionValue}`);
            return false;
         }
      } else {
         console.log(`No conversations attribute in User doc`);
         return false;
      }
      }, error => {
      console.log(`Unable to read User document: ${error}`);
      return false;
      });
   case "all-users":
      console.log(`No user can write to an all-users partitions`);
      return false;
   default:
      console.log(`Unexpected partition key: ${partitionKey}`);
      return false;
   }
};
```

To create these functions, select "Functions" and click "Create New Function." Make sure you type the function name precisely, set "Authentication" to "System," and turn on the "Private" switch (which means it can't be called directly from external services such as our mobile app):

    

### Linking User and Chatster Documents (Unchanged)

As described in [Building a Mobile Chat App Using Realm – Data Architecture, there are relationships between different `User` and `Chatster` documents. Now that we've defined the schemas and enabled Device Sync, it's convenient to add the Atlas Function and Trigger to maintain those relationships.

Create a Function named `userDocWrittenTo`, set "Authentication" to "System," and make it private. This article is aiming to focus on the iOS app more than the backend app, and so we won't delve into this code:

``` javascript
exports = function(changeEvent) {
   const db = context.services.get("mongodb-atlas").db("RChat");
   const chatster = db.collection("Chatster");
   const userCollection = db.collection("User");
   const docId = changeEvent.documentKey._id;
   const user = changeEvent.fullDocument;
   let conversationsChanged = false;
   console.log(`Mirroring user for docId=${docId}. operationType = ${changeEvent.operationType}`);
   switch (changeEvent.operationType) {
      case "insert":
      case "replace":
      case "update":
      console.log(`Writing data for ${user.userName}`);
      let chatsterDoc = {
            _id: user._id,
            partition: "all-users=all-the-users",
            userName: user.userName,
            lastSeenAt: user.lastSeenAt,
            presence: user.presence
      };
      if (user.userPreferences) {
            const prefs = user.userPreferences;
            chatsterDoc.displayName = prefs.displayName;
            if (prefs.avatarImage && prefs.avatarImage._id) {
               console.log(`Copying avatarImage`);
               chatsterDoc.avatarImage = prefs.avatarImage;
               console.log(`id of avatarImage = ${prefs.avatarImage._id}`);
            }
      }
      chatster.replaceOne({ _id: user._id }, chatsterDoc, { upsert: true })
      .then (() => {
            console.log(`Wrote Chatster document for _id: ${docId}`);
      }, error => {
            console.log(`Failed to write Chatster document for _id=${docId}: ${error}`);
      });

      if (user.conversations && user.conversations.length > 0) {
            for (i = 0; i < user.conversations.length; i++) {
               let membersToAdd = ];
               if (user.conversations[i].members.length > 0) {
                  for (j = 0; j < user.conversations[i].members.length; j++) {
                        if (user.conversations[i].members[j].membershipStatus == "User added, but invite pending") {
                           membersToAdd.push(user.conversations[i].members[j].userName);
                           user.conversations[i].members[j].membershipStatus = "Membership active";
                           conversationsChanged = true;
                        }
                  }
               }
               if (membersToAdd.length > 0) {
                  userCollection.updateMany({userName: {$in: membersToAdd}}, {$push: {conversations: user.conversations[i]}})
                  .then (result => {
                        console.log(`Updated ${result.modifiedCount} other User documents`);
                  }, error => {
                        console.log(`Failed to copy new conversation to other users: ${error}`);
                  });
               }
            }
      }
      if (conversationsChanged) {
            userCollection.updateOne({_id: user._id}, {$set: {conversations: user.conversations}});
      }
      break;
      case "delete":
      chatster.deleteOne({_id: docId})
      .then (() => {
            console.log(`Deleted Chatster document for _id: ${docId}`);
      }, error => {
            console.log(`Failed to delete Chatster document for _id=${docId}: ${error}`);
      });
      break;
   }
};
```

Set up a database trigger to execute the new function whenever anything in the `User` collection changes:

    

### Registering and Logging in from the iOS App

This section is virtually unchanged. As part of using the new Realm SDK features, there is now less in `AppState` (including fewer publishers), and so less attributes need to be set up as part of the login process.

We've now created enough of the backend app that mobile apps can now register new Realm users and use them to log into the app.

The app's top-level SwiftUI view is [ContentView, which decides which sub-view to show based on whether our `AppState` environment object indicates that a user is logged in or not:

``` swift
@EnvironmentObject var state: AppState
...
if state.loggedIn {
   if (state.user != nil) && !state.user!.isProfileSet || showingProfileView {
      SetProfileView(isPresented: $showingProfileView)
            .environment(\.realmConfiguration, app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
   } else {
      ConversationListView()
            .environment(\.realmConfiguration, app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
      .navigationBarTitle("Chats", displayMode: .inline)
      .navigationBarItems(
            trailing: state.loggedIn && !state.shouldIndicateActivity ? UserAvatarView(
               photo: state.user?.userPreferences?.avatarImage,
               online: true) { showingProfileView.toggle() } : nil
      )
   }
} else {
   LoginView()
}
...
```

When first run, no user is logged in, and so `LoginView` is displayed.

Note that `AppState.loggedIn` checks whether a user is currently logged into the Realm `app`:

``` swift
var loggedIn: Bool {
   app.currentUser != nil && user != nil && app.currentUser?.state == .loggedIn
}
```

The UI for LoginView contains cells to provide the user's email address and password, a radio button to indicate whether this is a new user, and a button to register or log in a user:

    

Clicking the button executes one of two functions:

``` swift
...
CallToActionButton(
   title: newUser ? "Register User" : "Log In",
   action: { self.userAction(username: self.username, password: self.password) })
...
private func userAction(username: String, password: String) {
   state.shouldIndicateActivity = true
   if newUser {
      signup(username: username, password: password)
   } else {
      login(username: username, password: password)
   }
}
```

`signup` makes an asynchronous call to the Realm SDK to register the new user. Through a Combine pipeline, `signup` receives an event when the registration completes, which triggers it to invoke the `login` function:

``` swift
private func signup(username: String, password: String) {
   if username.isEmpty || password.isEmpty {
      state.shouldIndicateActivity = false
      return
   }
   self.state.error = nil
   app.emailPasswordAuth.registerUser(email: username, password: password)
      .receive(on: DispatchQueue.main)
      .sink(receiveCompletion: {
            state.shouldIndicateActivity = false
            switch $0 {
            case .finished:
               break
            case .failure(let error):
               self.state.error = error.localizedDescription
            }
      }, receiveValue: {
            self.state.error = nil
            login(username: username, password: password)
      })
      .store(in: &state.cancellables)
}
```

The `login` function uses the Realm SDK to log in the user asynchronously. If/when the Realm login succeeds, the Combine pipeline sends the Realm user to the `chatsterLoginPublisher` and `loginPublisher` publishers (recall that we've seen how those are handled within the `AppState` class):

``` swift
private func login(username: String, password: String) {
   if username.isEmpty || password.isEmpty {
      state.shouldIndicateActivity = false
      return
   }
   self.state.error = nil
   app.login(credentials: .emailPassword(email: username, password: password))
      .receive(on: DispatchQueue.main)
      .sink(receiveCompletion: {
            state.shouldIndicateActivity = false
            switch $0 {
            case .finished:
               break
            case .failure(let error):
               self.state.error = error.localizedDescription
            }
      }, receiveValue: {
            self.state.error = nil
            state.loginPublisher.send($0)
      })
      .store(in: &state.cancellables)
}
```

### Saving the User Profile

On being logged in for the first time, the user is presented with SetProfileView.  (They can also return here later by clicking on their avatar.) This is a SwiftUI sheet where the user can set their profile and preferences by interacting with the UI and then clicking "Save User Profile":

    

When the view loads, the UI is populated with any existing profile information found in the `User` object in the `AppState` environment object:

``` swift
...
@EnvironmentObject var state: AppState
...
.onAppear { initData() }
...
private func initData() {
   displayName = state.user?.userPreferences?.displayName ?? ""
   photo = state.user?.userPreferences?.avatarImage
}
```

As the user updates the UI elements, the Realm `User` object isn't changed. It's not until they click "Save User Profile" that we update the `User` object. `state.user` is an object that's being managed by Realm, and so it must be updated within a Realm transaction. Using one of the new Realm SDK features, the Realm for this user's partition is made available in `SetProfileView` by injecting it into the environment from `ContentView`:

``` swift
SetProfileView(isPresented: $showingProfileView)
   .environment(\.realmConfiguration,
               app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
```

`SetProfileView` receives `userRealm` through the environment and uses it to create a transaction (line 10):

``` swift
...
@EnvironmentObject var state: AppState
@Environment(\.realm) var userRealm
...
CallToActionButton(title: "Save User Profile", action: saveProfile)
...
private func saveProfile() {
   state.shouldIndicateActivity = true
   do {
      try userRealm.write {
            state.user?.userPreferences?.displayName = displayName
            if photoAdded {
               guard let newPhoto = photo else {
                  print("Missing photo")
                  state.shouldIndicateActivity = false
                  return
               }
               state.user?.userPreferences?.avatarImage = newPhoto
            }
            state.user?.presenceState = .onLine
      }
   } catch {
      state.error = "Unable to open Realm write transaction"
   }
}
```

Once saved to the local Realm, Device Sync copies changes made to the `User` object to the associated `User` document in Atlas.

### List of Conversations

Once the user has logged in and set up their profile information, they're presented with the `ConversationListView`. Again, we use the new SDK feature to implicitly open the Realm for this user partition and pass it through the environment from `ContentView`:

``` swift
if state.loggedIn {
   if (state.user != nil) && !state.user!.isProfileSet || showingProfileView {
      SetProfileView(isPresented: $showingProfileView)
            .environment(\.realmConfiguration,
                           app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
   } else {
      ConversationListView()
            .environment(\.realmConfiguration, 
               app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
      .navigationBarTitle("Chats", displayMode: .inline)
      .navigationBarItems(
            trailing: state.loggedIn && !state.shouldIndicateActivity ? UserAvatarView(
               photo: state.user?.userPreferences?.avatarImage,
               online: true) { showingProfileView.toggle() } : nil
      )
   }
} else {
   LoginView()
}
```

ConversationListView receives the Realm through the environment and then uses another new Realm SDK feature (`@ObservedResults`) to set `users` to be a live result set of all `User` objects in the partition (as each user has their own partition, there will be exactly one `User` document in `users`):

``` swift
@ObservedResults(User.self) var users
```

ConversationListView displays a list of all the conversations that the user is currently a member of (initially none) by looping over `conversations` within their `User` Realm object:

``` swift
@ObservedResults(User.self) var users
...
private let sortDescriptors = 
   SortDescriptor(keyPath: "unreadCount", ascending: false),
   SortDescriptor(keyPath: "displayName", ascending: true)
]
...
if let conversations = users[0].conversations.sorted(by: sortDescriptors) {
   List {
      ForEach(conversations) { conversation in
            Button(action: {
               self.conversation = conversation
               showConversation.toggle()
            }) { ConversationCardView(conversation: conversation, isPreview: isPreview) }
      }
   }
   ...
}
```

At any time, another user can include you in a new group conversation.  This view needs to reflect those changes as they happen:

    

When the other user adds us to a conversation, our `User` document is updated automatically through the magic of Atlas Device Sync and our Atlas Trigger. Prior to Realm-Cocoa 10.6, we needed to observe the Realm and trick SwiftUI into refreshing the view when changes were received. The Realm/SwiftUI integration now refreshes the view automatically.

### Creating New Conversations

When you click in the new conversation button in `ConversationListView`, a SwiftUI sheet is activated to host `NewConversationView`. This time, we implicitly open and pass in the `Chatster` Realm (for the universal partition `all-users=all-the-users`:

``` swift
.sheet(isPresented: $showingAddChat) {
   NewConversationView()
      .environmentObject(state)
      .environment(\.realmConfiguration, app.currentUser!.configuration(partitionValue: "all-users=all-the-users"))
```

[NewConversationView creates a live Realm result set (`chatsters`) from the Realm passed through the environment:

``` swift
@ObservedResults(Chatster.self) var chatsters
```

`NewConversationView` is similar to `SetProfileView.` in that it lets the user provide a number of details which are then saved to Realm when the "Save" button is tapped.

In order to use the "Realm injection" approach, we now need to delegate the saving of the `User` object to another view (`NewConversationView` received the `Chatster` Realm but the updated `User` object needs be saved in a transaction for the `User` Realm):

``` swift
code content
SaveConversationButton(name: name, members: members, done: { presentationMode.wrappedValue.dismiss() })
   .environment(\.realmConfiguration,
                app.currentUser!.configuration(partitionValue: "user=\(state.user?._id ?? "")"))
```

Something that we haven't covered yet is applying a filter to the live Realm search results. Here we filter on the `userName` within the Chatster objects:

``` swift
@ObservedResults(Chatster.self) var chatsters
...
private func searchUsers() {
   var candidateChatsters: Results
   if candidateMember == "" {
      candidateChatsters = chatsters
   } else {
      let predicate = NSPredicate(format: "userName CONTAINScd] %@", candidateMember)
      candidateChatsters = chatsters.filter(predicate)
   }
   candidateMembers = []
   candidateChatsters.forEach { chatster in
      if !members.contains(chatster.userName) && chatster.userName != state.user?.userName {
            candidateMembers.append(chatster.userName)
      }
   }
}
```

### Conversation Status (Unchanged)

    

When the status of a conversation changes (users go online/offline or new messages are received), the card displaying the conversation details should update.

We already have a Function to set the `presence` status in `Chatster` documents/objects when users log on or off. All `Chatster` objects are readable by all users, and so [ConversationCardContentsView can already take advantage of that information.

The `conversation.unreadCount` is part of the `User` object, and so we need another Atlas Trigger to update that whenever a new chat message is posted to a conversation.

We add a new Atlas Function `chatMessageChange` that's configured as private and with "System" authentication (just like our other functions). This is the function code that will increment the `unreadCount` for all `User` documents for members of the conversation:

``` javascript
exports = function(changeEvent) {
   if (changeEvent.operationType != "insert") {
      console.log(`ChatMessage ${changeEvent.operationType} event – currently ignored.`);
      return;
   }

   console.log(`ChatMessage Insert event being processed`);
   let userCollection = context.services.get("mongodb-atlas").db("RChat").collection("User");
   let chatMessage = changeEvent.fullDocument;
   let conversation = "";

   if (chatMessage.partition) {
      const splitPartition = chatMessage.partition.split("=");
      if (splitPartition.length == 2) {
            conversation = splitPartition1];
            console.log(`Partition/conversation = ${conversation}`);
      } else {
            console.log("Couldn't extract the conversation from partition ${chatMessage.partition}");
            return;
      }
   } else {
      console.log("partition not set");
      return;
   }

   const matchingUserQuery = {
      conversations: {
            $elemMatch: {
               id: conversation
            }
      }
   };

   const updateOperator = {
      $inc: {
            "conversations.$[element].unreadCount": 1
      }
   };

   const arrayFilter = {
      arrayFilters:[
            {
               "element.id": conversation
            }
      ]
   };

   userCollection.updateMany(matchingUserQuery, updateOperator, arrayFilter)
   .then ( result => {
      console.log(`Matched ${result.matchedCount} User docs; updated ${result.modifiedCount}`);
   }, error => {
      console.log(`Failed to match and update User docs: ${error}`);
   });
};
```

That function should be invoked by a new database trigger (`ChatMessageChange`) to fire whenever a document is inserted into the `RChat.ChatMessage` collection.

### Within the Chat Room

    

[ChatRoomView has a lot of similarities with `ConversationListView`, but with one fundamental difference. Each conversation/chat room has its own partition, and so when opening a conversation, you need to open a new Realm. Again, we use the new SDK feature to open and pass in the Realm for the appropriate conversation partition:

``` swift
ChatRoomBubblesView(conversation: conversation)
   .environment(\.realmConfiguration, app.currentUser!.configuration(partitionValue: "conversation=\(conversation.id)"))
```

If you worked through Building a Mobile Chat App Using Realm – Integrating Realm into Your App, then you may have noticed that I had to introduce an extra view layer—`ChatRoomBubblesView`—in order to open the Conversation Realm.  This is because you can only pass in a single Realm through the environment, and `ChatRoomView` needed the User Realm. On the plus side, we no longer need all of the boilerplate code to open the Realm from the view's `onApppear` method explicitly.

ChatRoomBubblesView sorts the Realm result set by timestamp (we want the most recent chat message to appear at the bottom of the List):

``` swift
@ObservedResults(ChatMessage.self, 
   sortDescriptor: SortDescriptor(keyPath: "timestamp", ascending: true)) var chats.
```

The Realm/SwiftUI integration means that the UI will automatically refresh whenever a new chat message is added to the Realm, but I also want to scroll to the bottom of the list so that the latest message is visible. We can achieve this by monitoring the Realm. Note that we only open a `Conversation` Realm when the user opens the associated view because having too many realms open concurrently can exhaust resources.  It's also important that we stop observing the Realm by setting it to `nil` when leaving the view:

``` swift
@State private var realmChatsNotificationToken: NotificationToken?
@State private var latestChatId = ""
...
ScrollView(.vertical) {
   ScrollViewReader { (proxy: ScrollViewProxy) in
      VStack {
            ForEach(chats) { chatMessage in
               ChatBubbleView(chatMessage: chatMessage,
                              authorName: chatMessage.author != state.user?.userName ? chatMessage.author : nil,
                              isPreview: isPreview)
            }
      }
      .onAppear {
            scrollToBottom()
            withAnimation(.linear(duration: 0.2)) {
               proxy.scrollTo(latestChatId, anchor: .bottom)
            }
      }
      .onChange(of: latestChatId) { target in
            withAnimation {
               proxy.scrollTo(target, anchor: .bottom)
            }
      }
   }
}
...
.onAppear { loadChatRoom() }
.onDisappear { closeChatRoom() }
...
private func loadChatRoom() {
   scrollToBottom()
   realmChatsNotificationToken = chats.thaw()?.observe { _ in
      scrollToBottom()
   }
}

private func closeChatRoom() {
   if let token = realmChatsNotificationToken {
      token.invalidate()
   }
}

private func scrollToBottom() {
   latestChatId = chats.last?._id ?? ""
}
```

Note that we clear the notification token when leaving the view, ensuring that resources aren't wasted.

To send a message, all the app needs to do is to add the new chat message to Realm. Atlas Device Sync will then copy it to Atlas, where it is then synced to the other users. Note that we no longer need to explicitly open a Realm transaction to append the new chat message to the Realm that was received through the environment:

``` swift
@ObservedResults(ChatMessage.self, sortDescriptor: SortDescriptor(keyPath: "timestamp", ascending: true)) var chats
...
private func sendMessage(chatMessage: ChatMessage) {
   guard let conversataionString = conversation else {
      print("comversation not set")
      return
   }
   chatMessage.conversationId = conversataionString.id
   $chats.append(chatMessage)
}
```

## Summary

Since the release of Building a Mobile Chat App Using Realm – Integrating Realm into Your App, Realm-Swift 10.6 added new features that make working with Realm and SwiftUI simpler. Simply by passing the Realm configuration through the environment, the Realm is opened and made available to the view, and that view can go on to make updates without explicitly starting a transaction. This article has shown how those new features can be used to simplify your code. It has gone through the key steps you need to take when building a mobile app using Realm, including:

-   Managing the user lifecycle: registering, authenticating, logging in, and logging out.
-   Managing and storing user profile information.
-   Adding objects to Realm.
-   Performing searches on Realm data.
-   Syncing data between your mobile apps and with MongoDB Atlas.
-   Reacting to data changes synced from other devices.
-   Adding some backend magic using Atlas Triggers and Functions.

We've skipped a lot of code and functionality in this article, and it's worth looking through the rest of the app to see how to use features such as these from a SwiftUI iOS app:

-   Location data
-   Maps
-   Camera and photo library
-   Actions when minimizing your app
-   Notifications

We wrote the iOS version of the app first, but we plan on adding an Android (Kotlin) version soon—keep checking the developer hub and the repo for updates.

## References

-   GitHub Repo for this app
-   Read Building a Mobile Chat App Using Realm – Data Architecture to understand the data model and partitioning strategy behind the RChat app
-   Read Building a Mobile Chat App Using Realm – Integrating Realm into Your App if you want to know how to build Realm into your app without using the new SwiftUI featured in Realm-Cocoa 10.6 (for example, if you need to use UIKit)
-   If you're building your first SwiftUI/Realm app, then check out Build Your First iOS Mobile App Using Realm, SwiftUI, & Combine
-   GitHub Repo for Realm-Cocoa SDK
-   Realm Swift SDK documentation

>If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.