I have 3 functions like this:
func getMyFirstItem(complete: @escaping (Int) -> Void) {
DispatchQueue.main.async {
complete(10)
}
}
func getMySecondtItem(complete: @escaping (Int) -> Void) {
DispatchQueue.global(qos:.background).async {
complete(10)
}
}
func getMyThirdItem(complete: @escaping (Int) -> Void) {
DispatchQueue.main.async {
complete(10)
}
}
And I have a variable:
var myItemsTotal: Int = 0
I would like to know how to sum the items, in this case 10 10 10 to get 30. But what is the best way, since is background and main.
CodePudding user response:
I could be wrong, but I don't think it makes much difference about the different queues, you still have to "wait" until the completions are done, for example:
var myItemsTotal: Int = 0
getMyFirstItem() { val1 in
getMySecondtItem() { val2 in
getMyThirdItem() { val3 in
myItemsTotal = val1 val2 val3
print(" myItemsTotal: \(myItemsTotal)")
}
}
}
CodePudding user response:
func getMyFirstItem(complete: @escaping (Int) -> Void) {
DispatchQueue.main.async {
print("you are on main thread")
complete(10)
}
}
func getMySecondtItem(complete: @escaping (Int) -> Void) {
DispatchQueue.global(qos:.background).async {
print("you are on background thread")
complete(10)
}
}
func getMyThirdItem(complete: @escaping (Int) -> Void) {
DispatchQueue.main.async {
print("you are on main thread 2")
complete(10)
}
}
you can give a print statement to see the execution flow, to the value change print values in the function call's
getMyFirstItem(complete: {
value in
myItemsTotal = value
print(myItemsTotal)
})
getMySecondtItem(complete: {
value in
myItemsTotal = value
print(myItemsTotal)
})
getMyThirdItem(complete: {
value in
myItemsTotal = value
print(myItemsTotal)
})
each thread having their own priorities, if a task which need more time to execute we should add the task to background thread. if a task which need less time to execute we can add them in the main thread. its all up to the task execution time.
please keep in mind , the UI updation should happen in the main thread only