Nezih Yılmaz
Nezih Yılmaz

Reputation: 666

Realm notification does not fire for the initial value

I attach an observer to an object following way

let user = realm.object(ofType: User.self, forPrimaryKey: uid)

userNotificationToken = user.observe({ change in
        // Update UI            
    })

And I expect observation block to trigger on both the initial value AND updates. Yet it only triggers on updates. Does realm notifications work this way?

Upvotes: 1

Views: 691

Answers (1)

Jakir Hossain
Jakir Hossain

Reputation: 3930

I used Realm notification like below in my project and it works for me in both cases.

Step-1: Declare the NotificationToken like this.

var notificationToken: NotificationToken? = nil

Step-2: Here the main implementation of it.

func getChatLogsFromLocalDB(){
    messages = realm.objects(MessageDB.self).filter("contactId = '\(contactId)'" )

    notificationToken = messages.observe{ [weak self](change: RealmCollectionChange) in
        guard let tableview = self?.collectionView else {return}
        switch(change){
        case .initial:
            tableview.reloadData()
            print("initial....")
            break
        case .update(_, let deletions,let insertions,let modifications):
            print("update....)")
            tableview.beginUpdates()
            tableview.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
            tableview.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
            tableview.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
            tableview.endUpdates()
            self!.updateUI()
            break
        case .error(let error):
            print("Error in Realm Observer: \(error.localizedDescription)")
            break
        }
    }
}

Step-3: invalidate the notification token

deinit {
    notificationToken?.invalidate()
}

UPDATE

NOTE: In case of single object, observation block will only trigger on ObjectChange(change,deleted, error).

For further information see realm official documents about object-notifications

To Update UI initially, you can follow this way.

let user = realm.object(ofType: User.self, forPrimaryKey: uid)

updateUI(user) // initially update the UI

userNotificationToken = user.observe({ change in
    updateUI(user) // this block will only tigger when object will update            
})

func updateUI(user: User){
// implement your UI update logic here.
}

Upvotes: 2

Related Questions