dimanche 1 avril 2018

Using async data across different functions in Swift

So I'm currently fetching some remote JSON data through an async call. By using a completion handler I'm able to use the data outside the call.

But now I'm wondering how I could process this data the right way.

For example I'm having different functions that rely on this data. Every time I need the data I could call it inside these functions. E.g.:

func generateRandomItem() {
    DataManager().requestData() { (result: [Model]) in
        //Generate Random item from the results of call here
    }
}


func listAlphabetically() {
    DataManager().requestData() { (result: [Model]) in
        //List all data alphabetically from the results of the call here
    }
}

But this approach will be wasting API calls I think since the data will only change once a week.

Another approach I was thinking about, was calling this function on launch of the application and store everything in a global var. This var can then be used in every single function whenever I need it. E.g.:

var allItems = [Model]()

func getAllItems() {
    DataManager().requestData() { (result: [Model]) in
        self.allItems = result
    }
}

The disadvantage of this is that the data is only pulled in once, and never updated but only on app launch.

So this isn't much of a technical question but more a fundamental one. I'm pretty new to Swift and looking for the best design patterns. If my completion handler on the async call is also a wrong approach I would like to know how I could improve it!

Aucun commentaire:

Enregistrer un commentaire