Skip to main content

Finishing Sync

We have a problem: while syncing habits we're using our user id, but not while syncing our days. From the sync config code, these are the subscriptions we're adding:

SyncContentView.swift
                    subs.append(QuerySubscription<Days>(name: "user_days", query: { 
$0.ownerId == user.id
}))
subs.append(QuerySubscription<Day>())

subs.append(QuerySubscription<Habits>(name: "user_habits", query: {
$0.ownerId == user.id
}))
subs.append(QuerySubscription<Habit>())

When we add a Day we never set the ownerId because our model class Day doesn't have it. So when we insert a new Day it will appear for all users, as we're getting Day from all users, because we're not restricting the sync here:

SyncContentView.swift
                    subs.append(QuerySubscription<Day>())

So we need to do two things:

  • subscribe just to our Days
  • add the ownnerId when we create a new Day

Fixing the model: remove Days class​

Let's get rid of Days, as we don't really use that class for anything.

Add ownerId field to Day class​

We;ll add the ownerId field to the Day class.

Day.swift
import Foundation
import RealmSwift

public class Day: Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId

@Persisted var date = Date()
@Persisted var habits = RealmSwift.List<Habit>()

@Persisted var ownerId = ""

// ... same as before

Remove sync on Days and add sync info to Day​

We'll delete the sync subscription on Days (as we just deleted that class) and add the correct subscription for Day.

SyncContentView.swift
        if let foundSubscription = subs.first(named: "user_days") {
return
} else {
subs.append(QuerySubscription<Day>(name: "user_days", query: {
$0.ownerId == user.id
}))

subs.append(QuerySubscription<Habits>(name: "user_habits", query: {
$0.ownerId == user.id
}))
subs.append(QuerySubscription<Habit>())
}

Set ownerId while creating a new Day​

DaysView.swift
    let day = Day.createDayWithHabitsInRealm(realm: realm)

day.ownerId = realm.syncSession?.parentUser()?.id ?? ""
try? realm.write({
$days.append(day)
})

Add ownerId when creating the initial set of Habits​

MainView.swift
    ProgressView()
.onAppear {
let habits = Habits()
habits.ownerId = realm.syncSession?.parentUser()?.id ?? ""
$allHabitGroups.append(habits)
}

Testing it​

Now if we run the app new days are not appearing in other users' apps.