Skip to content

Commit

Permalink
Use the block based KVO API in AsyncOperation
Browse files Browse the repository at this point in the history
  • Loading branch information
buggmagnet committed Sep 4, 2023
1 parent 9cc7c2e commit 52c06cb
Showing 1 changed file with 7 additions and 29 deletions.
36 changes: 7 additions & 29 deletions ios/Operations/AsyncOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ open class AsyncOperation: Operation {
_error
}

override public final var isReady: Bool {
dynamic override public final var isReady: Bool {
stateLock.lock()
defer { stateLock.unlock() }

Expand Down Expand Up @@ -238,45 +238,23 @@ open class AsyncOperation: Operation {

public let dispatchQueue: DispatchQueue

private var isReadyObserver: NSKeyValueObservation?
public init(dispatchQueue: DispatchQueue? = nil) {
self.dispatchQueue = dispatchQueue ?? DispatchQueue(label: "AsyncOperation.dispatchQueue")
super.init()

addObserver(
self,
forKeyPath: #keyPath(isReady),
options: [],
context: &Self.observerContext
)
isReadyObserver = observe(\.isReady, options: []) { operation, _ in
operation.checkReadiness()
}
}

deinit {
removeObserver(self, forKeyPath: #keyPath(isReady), context: &Self.observerContext)
// Clear the observer when the operation is deallocated to avoid leaking memory.
isReadyObserver = nil
}

// MARK: - KVO

private static var observerContext = 0

override public func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
if context == &Self.observerContext {
checkReadiness()
return
}

super.observeValue(
forKeyPath: keyPath,
of: object,
change: change,
context: context
)
}

@objc class func keyPathsForValuesAffectingIsReady() -> Set<String> {
[#keyPath(state)]
}
Expand Down

0 comments on commit 52c06cb

Please sign in to comment.