user125972 user125972 - 2 months ago 16
iOS Question

Timing of async callback

I want to have a better idea about the timing of the completion block from a intenet download request. In this case firebase. The following code example does not do anything, but it illustrates my questions.

Say I have 100 values in keysArray, there would be 100 async request to firebase and the completion block will be executed 100 times

func someFunction() {
for keys in keysArray {
loadDataFromFirebaseWithKey(completionHandler: { (success, data) in

print(data)

// Task A Some length for loop
for i in 0...10000 {
print("A")
}

// Task B
for i in 10001...20000 {
print("B")
}
})

// Task C
for i in 20001...30000 {
print("C")
}

// Task D
for i in 30001...40000 {
print("D")
}
}
// Task E
for i in 40001...50000 {
print("E")
}

// Task F
for i in 50001...60000 {
print("F")
}
}


The reason I am using such a big for loop is to illustrate some time consuming/non async proccess. Here are three case that I was wondering


  1. Say if the program is half way through task C, does it finish C and also D before going into the completion block to do A and B

  2. Say if the program is half way through task E, does it finish E and also F before going into the completion block to do A and B


Answer

If tasks are running concurrently, they may replace each other as the active thing at an opportunity, and may just proceed with genuine concurrency given that all iOS devices since the 4s have multiple cores. There's no reason that any particular for loop will be at any specific point at the time of interruption.

If Firebase schedules its completion handlers on a serial queue then none of the handlers will overlap with any other.

If Firebase schedules its completion handlers on the main queue, and you're calling it from the main queue, neither its completion handlers nor your calling code will overlap with each other.

So, directly to answer:

  1. yes if Firebase is scheduling completion handlers on the same queue as you called from and that queue is serial — which almost always means 'yes' if everything is main queue linked. Otherwise no.

  2. same answer. There's no special concurrency magic to for loops. They're exactly as usurpable as any other piece of code.

Comments