How to combine KVO notifications with thread safety?

Viewed 67

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?

0 Answers
Related