Subscriptions to Flexible Sync not updating @ObservedResults

I’m having some trouble integrating my Realm-based iOS app with Device Sync. I’ve confirmed that I’m writing to the synced realm successfully as I can see the results on the Mongo DB dashboard, but my subscriptions don’t seem to be working. cycles is always empty, even immediately after adding a cycle to the realm. Not sure if my schema or something else on the backend could be a problem but any help would be greatly appreciated as I’m at my wit’s end.

syncedRealm.subscriptions.count is 2 as expected.
permissions are set such that all users can read and write all data.

import Foundation
import RealmSwift
import Realm

class RealmManager: ObservableObject {
    private(set) var syncedRealm: Realm?
    @ObservedResults(Cycle.self, sortDescriptor: "startDate") var cycles
    @ObservedResults(Day.self, sortDescriptor: "date") var days
    let app = App(id: "redacted")
    var loggedInUser: User? = nil
    
    init() {
        print(Realm.Configuration.defaultConfiguration.fileURL as Any)
        Task.init {
            try await login()
            if let user = loggedInUser {
                try await openSyncedRealm(user: user)
            }
        }
    }
    
    @MainActor
    func login() async throws {
        do{
            let user = try await app.login(credentials: Credentials.anonymous)
            print("Successfully logged in user: \(user) with id : \(user.id)")
            self.loggedInUser = user
        } catch {
            print("Failed to log in user: \(error)")
        }
    }
    
    @MainActor
    func openSyncedRealm(user: User) async throws {
        do {
            var config = user.flexibleSyncConfiguration()
            config.objectTypes = [Cycle.self, Day.self]
            let realm = try await Realm(configuration: config, downloadBeforeOpen: .never)
            let subscriptions = realm.subscriptions
            try await subscriptions.update {
                if let currentSubscription = subscriptions.first(named: "cycles") {
                    print("Replacing subscription for cycles")
                    currentSubscription.updateQuery(toType: Cycle.self)
                } else {
                    print("Appending subscription for cycles")
                    subscriptions.append(QuerySubscription<Cycle>(name: "cycles"))
                }
                if let currentSubscription = subscriptions.first(named: "days") {
                    print("Replacing subscription for days")
                    currentSubscription.updateQuery(toType: Day.self) { day in
                        day.ownerID == user.id
                    }
                } else {
                    print("Appending subscription for days")
                    subscriptions.append(QuerySubscription<Day>(name: "days") { day in
                        day.ownerID == user.id
                    })
                }
            }
            self.syncedRealm = realm
            print("Successfully opened realm")
        } catch {
            print("Error opening realm: \(error.localizedDescription)")
        }
    }

Hi, can you send the link to your app. It will look like https://realm.mongodb.com/groups/${}/apps/${}? I can see if there is anything interesting going on. Is there data in your cluster that you would expect to be send back for cycles?

Hi Tyler, here’s the link: App Services

Yes, in Collections under the cluster I can see cycle objects written by the client that should be getting sent back

Turns out @ObservedResults only works inside views in SwiftUI. Would have been tremendously helpful if this was mentioned in the documentation.

My apologies for not getting back to you. Must have slipped through the cracks. I have just filed a documentation ticket to make this clearer.

Best,
Tyler

1 Like

Hey @Violeta_Druga - sorry our docs let you down! I’m thinking about where to make this clearer, and am wondering where you encountered documentation for @ObservedResults. Was it the SwiftUI React to Changes page that was unclear, or the autogenerated API reference, or somewhere else?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.