Home > Mobile >  Mutating conditional in DispatchQueue.main.asyncAfter behavior
Mutating conditional in DispatchQueue.main.asyncAfter behavior

Time:11-26

I have a question regarding the behaviour of the DispatchQueue, particularly how asyncAfter would behave if you'd use a conditional of some published var that might change within the completion handler.

Let's say when the DispatchQueue is called, viewModel.someBool = true, but sometime during these 3.5 seconds, a function, that takes quite some time, is called that sets viewModel.someBool to false. Will the DispatchQueue always wait until all previous code is done executing, or is there any scenario in which the completion handler can run "in between" some other block of codes execution? All code is being run on the main thread, but I am still uncertain if this could cause bugs or not.

DispatchQueue.main.asyncAfter(deadline: .now()   3.5) {
     if viewModel.someBool {
          // do something
     }
}

CodePudding user response:

Will the DispatchQueue always wait until all previous code is done executing, or is there any scenario in which the completion handler can run "in between" some other block of codes execution?

Depends if it's a Sequential queue or Concurrent queue. Sequential queue will finish task1 before starting task2; concurrent may run them in parallel. main thread is sequential, so you are good there, but...

You said yourself "sometime during these 3.5 seconds a function is called that sets viewModel.someBool to false". What if that "some time" is 1 nanosecond after a delayed task was picked up and started running?.. So now your function that changes viewModel.someBool to false needs to wait for your delayed task to complete.

So either this should be OK for your code (which is preferable, since such a strong dependency on order, especially in UI, usually means some design issues), or you need to guarantee the order in your code

  • Related