Flexible configuration
Configuring Flexible Configuration
We'll add code to configure our connection from Mobile to MongoDB Atlas in a way that only data for this user is requested. This way we avoid downloading data from other users and the connection is much more efficient.
To do that, once we have a user
logged in, we add a flexibleSyncConfiguration
to that user. This contains a list of subscriptions (called subs
here). Each subscription is a query and can be much more complex than showcased here. For instance, we can be interested in data for this user, but just the last three months, not all data.
Each subscription has an identifier, and here we'll only have one, called user_days
. We're using the queryable field ownerId
that we added to our subscriptions in App Services > Flexible Configuration > Configure Queryable Fields
// ...
if let user = app.currentUser {
// Create a `flexibleSyncConfiguration` with `initialSubscriptions`.
// We'll inject this configuration as an environment value to use when opening the realm
// in the next view, and the realm will open with these initial subscriptions.
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
// Check whether the subscription already exists. Adding it more
// than once causes an error.
if let foundSubscriptions = subs.first(named: "user_days") {
// Existing subscription found - do nothing
return
} else {
// Add queries for any objects you want to use in the app
// Linked objects do not automatically get queried, so you
// must explicitly query for all linked objects you want to include
subs.append(QuerySubscription<Days>(name: "user_days", query: {
// Query for objects where the ownerId is equal to the app's current user's id
// This means the app's current user can read and write their own data
$0.ownerId == user.id
}))
subs.append(QuerySubscription<Day>())
subs.append(QuerySubscription<Habits>(name: "user_habits", query: {
// Query for objects where the ownerId is equal to the app's current user's id
// This means the app's current user can read and write their own data
$0.ownerId == user.id
}))
subs.append(QuerySubscription<Habit>())
}
})
} else {
// ...
}