J.Arji
J.Arji

Reputation: 661

Grand Central Dispatch (GCD) in swift

I'm familiar with using AsyncTask in Android: create a subclass, call execute on an instance of the subclass and onPostExecute is called on the UI thread or main thread. What's the equivalent in swift??

Upvotes: 5

Views: 1718

Answers (2)

Logan
Logan

Reputation: 53112

This solves most of my async requirements in Swift:

public func background(function: @escaping () -> Void) {
    DispatchQueue.global().async(execute: function)
}

public func main(function: @escaping () -> Void) {
    DispatchQueue.main.async(execute: function)
}

Then use like:

background {
    // I'm in the background
    main {
        // I'm back on Main
    }
}

For example:

background { [weak self] in
    let result = longOperationToFetchData()
    main {
        self?.data = result.data
        self?.reloadTableView()
    }
}

Upvotes: 11

Albert
Albert

Reputation: 331

I think using NSOperationQueue is more elegant and simple. You create a queue:

var queue = NSOperationQueue()

And create task:

let operation = NSBlockOperation { () -> Void in
// Perform your task
}

After that, put your task in queue

queue.addOperation(operation)

That is. In case you want perform UI-related task, using this code block:

NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
// UI related task
}

NSOperationQueue offers you the simple way to set dependency between tasks. For example, you have 4 task, op1, op2, op3, op4. And you want that op1 needs to be done before op2, then you can write like this:

op2.addDependency(op1)

Then op2 will be fired after op1 done. Since there is no dependency for op3 and op4, it could be done before/or after op2

Upvotes: 3

Related Questions