0

I have a data sync which should happen in a background thread in a sequential order as one task need to finish prior start syncing the next. I tried executing in a Dispatch queue. But then as the process scheduler decides what to execute first i ran in to lots of issues. My partial code as bellow.

  DispatchQueue.main.async(execute: {
       SyncAgent.shared.initDataSync()
  }) 


 func initDataSync() {

  //These are not executing in the order. My objective is to make this happen sequentially in the background and notify the relevant screens once its completed. 
   syncUsers()
   syncDevices()
   syncAccouts()
   syncLocations()

 }
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
danu
  • 1,079
  • 5
  • 16
  • 48
  • Provide a [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example). – Frankenstein Jul 23 '20 at 14:52
  • You need to handle the completions to call next one. ex. `syncUser(completion: () -> Void)` – Omer Faruk Ozturk Jul 23 '20 at 15:06
  • Please, include more details in your question. What if `syncUsers()` fails? Should it continue? Should it stop? There're many ways, but unless you clarify what your **exact** problem is, there's no way to answer this question. You can use `Combine`, `OperationQueue` & `Operation` & dependencies, ... – zrzka Jul 23 '20 at 15:19

1 Answers1

0

To run your function in a background thread (or say, any thread other than the main thread), you can try creating a custom DispatchQueue.

For example:

    let myQueue = DispatchQueue(label: "serial") // DispatchQueue is serial by default
    myQueue.async {
        // 1st function
    }
    myQueue.async {
        // 2nd function
    }

The serial DispatchQueue ensures the function you push into it is called in the order it was pushed.

But if you want the second function to wait for the result of the first function, you can, for example, add a completionHandler to each function to call the next function when finished:

    func doSomething(completionHandler: () -> Void) {
        // do something
        // ...
        // call completionHandler when everything is finished
        completionHandler()
    }

Or use DispatchGroup to notify when each job's done. It really depends on the complexity of your task. (Also, the Operation API is another flexible tool to handle concurrency task.)

Victor Gama
  • 35
  • 1
  • 5
paky
  • 595
  • 1
  • 5
  • 18
  • 1
    Bear in mind that a serial queue won't guarantee order of execution for async functions. It can only guarantee serial execution for synchronous functions. – Dávid Pásztor Jul 23 '20 at 15:28
  • Thanks for making it clear. That's what I want to mention in the latter part, but maybe my poor english didn't explain it clearly. – paky Jul 23 '20 at 15:42