Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the block based KVO API in AsyncOperation #5077

Merged
merged 1 commit into from
Sep 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any particular reason why that has to be marked dynamic?

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
Loading