user6914372
user6914372

Reputation:

Swift threading multiple tasks?

I have this label that is supposed to display a username. Now, I have done quite a bit of IOS developing, however threading is still a bit unclear to me. How would I make sure this code finishes:

User(name: "", email: "", _id: "").getCurrentUser(userId: userId)

Before this gets excecuted?:

self.nameLabel.text = currentUser.name

I have been fumbling with DispatchQueue but I can't seem to figure it out... Thx in advance!

Upvotes: 2

Views: 1112

Answers (3)

Brian Trzupek
Brian Trzupek

Reputation: 5380

You can use DispatchGroups to do this, as one solution. Here is an example:

// create a dispatch group
let group = DispatchGroup()

// go "into that group" starting it
group.enter()

// setup what happens when the group is done
group.notify(queue: .main) {
    self.nameLabel.text = currentUser.name
}

// go to the async main queue and do primatry work.
DispatchQueue.main.async {
    User(name: "", email: "", _id: "").getCurrentUser(userId: userId)
    group.leave()
}

Upvotes: 1

Rool Paap
Rool Paap

Reputation: 1976

Just send a notification in your getCurrentUser() method and add an observer in your UIViewController to update the label.

public extension Notification.Name {
    static let userLoaded = Notification.Name("NameSpace.userLoaded")
}

let notification = Notification(name: .userLoaded, object: user, userInfo: nil)
NotificationCenter.default.post(notification)

And in your UIViewController:

NotificationCenter.default.addObserver(
        self,
        selector: #selector(self.showUser(_:)),
        name: .userLoaded,
        object: nil)

func showUser(_ notification: NSNotification) {
    guard let user = notification.object as? User,
        notification.name == .userLoaded else {
            return
    }
    currentUser = user
    DispatchQueue.main.async {
        self.nameLabel.text = self.currentUser.name
    }
}

Upvotes: 0

Adam
Adam

Reputation: 4818

You have to differentiate synchronous from asynchronous tasks. Typically, a synchronous task is a task blocking the execution of the program. The next task will not be executed until the previous one finishes. An asynchronous task is the opposite. Once it is started, the execution passes to the next instruction and you get typically the results from this task with delegating or blocks.

So without more indication, we can't know what exactly getCurrentUser(:) do...

According to Apple :

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

It is not necessarily executing work items on background threads. It is just a structure allowing you to execute synchronously or asynchronously work items on queues (it could be the main queue or another one).

Upvotes: 0

Related Questions