user4992124
user4992124

Reputation: 1594

Observing realm changes are not firing

In my application I have a custom RealmDatabase class. It initializes the Realm database for me.

public class RealmDatabase: Database {
    let realm: Realm

    //
    // I also provide a shared() singleton
    //

    public init(fileURL: URL) {
        let config = Realm.Configuration(fileURL: fileURL)
        Realm.Configuration.defaultConfiguration = config
        realm = try! Realm()
    }

    public func observe<T>(_ block: @escaping ((T) -> Void), for object: T.Type) where T : Storable {
        realm.objects(object).observe { (changes) in
            print("Changes: ", changes)
        }
    }
}

Now, I also wrote a class called SyncEngine so that I can start syncing with CloudKit. The class looks like this:

public class SyncEngine: NSObject {
    private let database: Database

    public init(database: Database) {
        self.database = database
        super.init()
    }

    public func start() {
        database.observe({ restaurant in
            print("changes!")
        }, for: Restaurant.self)
    }
}

Now, in my AppDelegate I do the following:

let database = RealmDatabase.shared()
let syncEngine = SyncEngine(database: database)
syncEngine.start()

The problem, though, is that my observer is never fired and print("Changes: ", changes) is never printed to the console. I don't know what I'm doing wrong, though. Any ideas?

Upvotes: 2

Views: 1209

Answers (1)

Oscar Apeland
Oscar Apeland

Reputation: 6662

You're discarding the observation as you create it. To solve this, you need to retain the NotificationToken returned by observe.

var token: NotificationToken? 

func start() {
    token = database.observe { changes in ... }
}

Upvotes: 8

Related Questions