Search code examples
swiftalamofirensoperationqueue

what is the best way to combine some Alamofire to queue?


I'm new to Swift and know almost nothing about threads, operations, queues, etc. And I have for example initial page in my app, where I use 3 alamofire requests like so:

request1 => request2

request3

                     => segue to the next view

It means, that requests 1 and 2 are serial, but 3 can be parallel, and segue only when ALL requests are done and handled.

I've tried OperationsQueue and at least it was faster =) but at Xcode's console I see that some code inside both Alamofire's success case's are done after segue was perform.

So what is the best practice to combine up to 5 Alamofire without make them nested? Or how correct handle async functions with OperationQueue?


Solution

  • DispatchGroup can sometimes cause problems like deadlock. You can use completion block. Completion block funcs are async functions.

    func 1(completion:@escaping () -> ()) {
    
       func 2(completion:@escaping () -> ()) {
    
          func 3(completion:@escaping () -> ()) {
    
           //You dont never know when func1 is finished. So you have to write nested functions. 
           //In this situation func2 waits func1. And func3 wait for func1 and func2. 
           //You can write the func3 at the top. This is you choice. 
          }
    
       }
    
    }