In Android, we have mutable live data object when we update it let say on a different thread we attached to it an observer. When the object gets updated the observer is listening and update the UI accordingly.
liveDataService.setValue(response); ==> updating the object with new data
And in the Activity(let say like TableViewController for swift/IOS)
We put the observer
liveDataService.observeForever(s -> {
Log.d(TAG, getString(R.string.service_observer_message));
updateUI(s);
}); ==> When liveDataService changes we update the UI
Now I want to do the same for Swift/IOS
I see the function
addObserver(_:forKeyPath:options:context:)
But I can not attach it to an Array that gets the update in the background only to NSObject
What is the best method to accomplish this task?
Thanks Eran
As per my understanding, you should use local notifications for sending data with addObserver and postNotification to achieve this. find sample code for same.
let imageData:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData)
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.receiveData(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func receiveData(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
}
}
You can use didSet property observe. It respond when property value change.
var dataArray = [String]() {
didSet {
print(“Array Count = \(dataArray.count)”)
}
}
when you append data in dataArray its call the dataArray property observe and print the Array Count
There are multiple ways how to do that.
The one that's closest to your Android solution should be Key Value Observing: https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift
If you want to read more about that topic: https://www.swiftbysundell.com/posts/observers-in-swift-part-1