2

I am trying to get a queue that executes serially, wether its queued items are synchronous or asynchronous.

The idea is that one of the functions returns a block. That block should somehow be queued onto the serial queue and dequeued when executed to let subsequent work items through. Here is an example of what I am trying to achieve:

let serialQueue = DispatchQueue(label: "print.serial.queue")

var i = 0

override func viewDidLoad() {
    super.viewDidLoad()

    printSomething() // Executes immediately
    printSomething() // Executes immediately
    let completion = printSomethingWithClosure() // Will execute when the closure is called
    printSomething() // Queued because completion hasn't been called yet
    printSomething() // Queued because completion hasn't been called yet
    completion() // The closure is executed, the queue can move on to the next work item

    // Expected output:
    // serial 1
    // serial 2
    // serial 3 (closure called)
    // serial 4
    // serial 5

}

func printSomething(){
    let workItem = DispatchWorkItem(qos: .userInitiated, flags: .assignCurrentContext) {[unowned self] in
        print("serial \(self.i)")
        self.i = self.i + 1
    }
    serialQueue.sync(execute: workItem)
}

func printSomethingWithClosure() -> (() -> ()){

    let completionHandler = {
        print("serial \(self.i) (closure called)")
        self.i = self.i + 1
    }

    // How do I queue this onto the DispatchQueue so it gets executed when the completionHandler is called?

    return completionHandler
}

Is this possible?

Erken
  • 1,448
  • 16
  • 23
  • This can be done in objective-c and swift 2.3 using `NSOperation` subclass. In swift 3, it seems that we can't subclass `Operation` (`NSOperation`). So, I am not sure how we can go about it in swift 3. Did you find any solution for this? – KrishnaCA Dec 02 '16 at 17:30
  • @KrishnaCA Not yet unfortunately, but I'll post here if I do! – Erken Dec 02 '16 at 22:27
  • I can provide solution for achieving this for objective-c which you can use in swift 3 through bridging header – KrishnaCA Dec 03 '16 at 06:23
  • @KrishnaCA OK, can you post your solution please? I'll see if I can translate your objective-C code into Swift 3. – Erken Dec 05 '16 at 10:21
  • check my answer for this question. http://stackoverflow.com/questions/40265055/cancellable-set-of-asynchronous-operations-with-progress-reporting-in-ios. If you have any doubts, feel free to ask – KrishnaCA Dec 05 '16 at 12:11

0 Answers0