MFAXXI
MFAXXI

Reputation: 11

How do I perform an action after receiving data from two asynchronous functions? Swift

I execute 2 http requests and get data from them asynchronously. After the data is received, I need to form an array based on it and reload the table, how do I do this? Code:

override func viewDidLoad() {
        super.viewDidLoad()
        
        ApiManager.shared.getStocks(completion: {result in
            DispatchQueue.main.async {
                switch result {
                case .success(let stocks):
                    self.stocks = stocks
                case .failure:
                    self.stocks = []
                }
            print(self.stocks.count)
            }
        })
        ApiManager.shared.getDowJones (completion: { result in
            DispatchQueue.main.async {
                switch result {
                case .success(let dowJones):
                    self.dowJones = dowJones
                case .failure:
                    self.dowJones = []
                }
                print(self.dowJones.prefix(10))
            }
        })
    }

Upvotes: 0

Views: 51

Answers (2)

ami solani
ami solani

Reputation: 371

You can take one dynamic variable as APISuccess and then fire that when you get API success, now all you need to do is bind that variable in your view controller and write a code indise it's bolck.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

Best fit DispatchGroup

   let g = DispatchGroup()
   g.enter()
    ApiManager.shared.getStocks(completion: {result in
        DispatchQueue.main.async {
            switch result {
            case .success(let stocks):
                self.stocks = stocks
            case .failure:
                self.stocks = []
            }
        g.leave()
        print(self.stocks.count)
        }
    })
   g.enter()
    ApiManager.shared.getDowJones (completion: { result in
        DispatchQueue.main.async {
            switch result {
            case .success(let dowJones):
                self.dowJones = dowJones
            case .failure:
                self.dowJones = []
            }
            g.leave()
            print(self.dowJones.prefix(10))
        }
    })

    g.notify(queue:.main) {
        // reload here
     }

Upvotes: 5

Related Questions