How can I make an NSOperationQueue (or anything else) wait for two async network calls with callbacks? The flow needs to look like this
Block Begins {
Ne
AsyncOperation maintains its state w.r.t to Operation own state. Since the operations are of asynchronous nature. We need to explicitly define the state of our operation. Because the execution of async operation returns immediately after it's called. So in your subclass of AsyncOperation you just have to set the state of the operation as finished in your completion handler
class AsyncOperation: Operation {
public enum State: String {
case ready, executing, finished
//KVC of Operation class are
// isReady, isExecuting, isFinished
var keyPath: String {
return "is" + rawValue.capitalized
}
}
//Notify KVO properties of the new/old state
public var state = State.ready {
willSet {
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
}
didSet{
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
}
extension AsyncOperation {
//have to make sure the operation is ready to maintain dependancy with other operation
//hence check with super first
override open var isReady: Bool {
return super.isReady && state == .ready
}
override open var isExecuting: Bool {
return state == .executing
}
override open var isFinished: Bool {
return state == .finished
}
override open func start() {
if isCancelled {
state = .finished
return
}
main()
state = .executing
}
override open func cancel() {
super.cancel()
state = .finished
} }
Now to call if from your own Operation class
Class MyOperation: AsyncOperation {
request.send() {success: { (dataModel) in
//waiting for success closure to be invoked before marking the state as completed
self.state = .finished
} }