5

How do I combine KVO notifications with thread safety? I have a class that needs to be KVO compliant and this is how I currently do it:

class CustomOperation: Operation {
    private let stateQueue = DispatchQueue(label: "customOperation", attributes: .concurrent)
    private var _isExecuting = false
    
    override var isExecuting: Bool {
        get {
            return stateQueue.sync { _isExecuting }
        }
        set {
            stateQueue.async(flags: .barrier) {
                self._isExecuting = newValue
            }
        }
    }
    
    override func start() {
        willChangeValue(forKey: "isExecuting")
        isExecuting = true
        didChangeValue(forKey: "isExecuting")
    }
}

Can I move the notifications inside the property setter, like so?

class CustomOperation: Operation {
    private let stateQueue = DispatchQueue(label: "customOperation", attributes: .concurrent)
    private var _isExecuting = false
    
    override var isExecuting: Bool {
        get {
            return stateQueue.sync { _isExecuting }
        }
        set {
            stateQueue.async(flags: .barrier) {
                self.willChangeValue(forKey: "isExecuting")
                self._isExecuting = newValue
                self.didChangeValue(forKey: "isExecuting")
            }
        }
    }
    
    override func start() {
        isExecuting = true
    }
}

And does either example correctly combine KVO notifications with thread safety?

lurning too koad
  • 2,698
  • 1
  • 17
  • 47
  • Which version of iOS are you supporting? Have you tried using actors? – bsarrazin Dec 28 '21 at 05:18
  • Basically you get KVO notifications for free by marking a property `@objc dynamic`. You can find a robust implementation of a thread-safe asynchronous operation [here](https://stackoverflow.com/questions/43561169/trying-to-understand-asynchronous-operation-subclass). – vadian Dec 28 '21 at 05:41

0 Answers0