1

I'm generating a ticker which retrieves data from the api using dataTask and returns to the function via succsss

The function which gets the response needs to append or concatenate them in sequence, however I'm unable to get that done.

Here is what I've tried, both fail as the last print line executes before the individual ticker success call returns.

    func getTicker() {

        var tickerText = ""

        tickerText += dataRequestnew("https://api-path-here/1") { success in return "First-item: \(success)" }
        tickerText += dataRequestnew("https://api-path-here/2") { success in return " | Second-item: \(success)" }

        print(tickerText)

    }

Or

    var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            print(self.tickerText)
        }
        dataRequestnew("https://api-path-here/2") { success in
            self.tickerText += " | Second-item: \(success)"
            print(self.tickerText)
        }

        print(self.tickerText)
    }

In the second example, the individual ticker prints successfully, but not the last one, it returns the default value only.

Question

How can I make the code run in sequence or at least make sure that the last print works once all the tickerText calls are returned successfully.

Thanks.

Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37

2 Answers2

1

As an option, you can call the second request in first response. And only then print a result.

var tickerText = ""

    func getTicker() {

        dataRequestnew("https://api-path-here/1") { success in
            self.tickerText += "First-item: \(success)"
            dataRequestnew("https://api-path-here/2") { success in
                self.tickerText += " | Second-item: \(success)"
                print(self.tickerText)
            }
        }       
    }
Bogdan Ustyak
  • 5,639
  • 2
  • 21
  • 16
  • this crossed my mind, but it's not practicle if I have a lot of items imho, any other suggestions please? – Nabeel Khan Jun 05 '17 at 01:23
  • Actually, the best option, in my opinion, is to use ReactiveX https://github.com/ReactiveX/RxSwift. You can transform your requests into data streams and flat map them to have a single concatenated response at the end. You can find a clear example how to implement it here: https://stackoverflow.com/questions/40919920/proper-usage-of-rxswift-to-chain-requests-flatmap-or-something-else – Bogdan Ustyak Jun 05 '17 at 14:20
0

Crate a serial queue. Dispatch the requests on that queue.

let serialQueue = DispatchQueue(label: "com.mydomain.purpose")
    serialQueue.async {
       // some code
    }
    serialQueue.async {
        // some code
    }
Mohammad Sadiq
  • 5,070
  • 28
  • 29