0

I want to asynchronously load some data when my app starts and use the loaded data from a view controller that's presented later on in the apps' flow.

How do I determine if the data has loaded and, if it hasn't, how do I wait for it to load?

So if in AppDelegate the code is... _ = service.LoadData() and this returns a promise, how would the view controller know if the promise has returned or not?

Adding a new .then call onto the end of the promise would surely not work if the promise has already returned.

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • can't we create `completionHandlers` i.e. `closures` – Rajan Maheshwari Oct 13 '16 at 19:04
  • Yes, but you don't know if the task has completed or not. If its completed, then a completion closure isn't going to be called. – Ian Warburton Oct 13 '16 at 19:08
  • I think the only way to let your `ViewController` know is to add an observer in your `ViewController` and fire a notification as soon as promise returns. Use the `NSNotificationCenter` – Rajan Maheshwari Oct 13 '16 at 19:10
  • But the notification may have already been sent by the time the view controller is loaded. – Ian Warburton Oct 13 '16 at 19:12
  • okay, then save the data in some database medium like `CoreData` or some shared preferences like `UserDefaults` when promise returns. Don't remove the observers as there might be a case that your controller is loaded and till that time your promise is not returned. On arriving to controller check whether anything is there in CoreData and do your stuff. If there is nothing, then we have an observer listening – Rajan Maheshwari Oct 13 '16 at 19:14

1 Answers1

0

Calling .then on a resolved promise seems to result in the closure being called immediately. So I just store the promise from the initial query, and then append a new .then to it whenever. If the data is loaded, its returned immediately, otherwise, hopefully, it will wait.

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189