danieltmbr
danieltmbr

Reputation: 1042

Wait a closure to complete in the middle of a function chaining in SWIFT

I was wondering whether I can wait for a closure to end in function chaining before the code runs towards the next function.

For example:

SomeSingletonClass.sharedInstance.bFunction()

And if it's the first call of the sharedInstance, I'd like bFunction() to wait until a closure* in the init() of SingletonClass ends. Is it possible somehow without blocking the UI?

*This closure may show a Grant Access Authorisation Alert, and the bFunction() should wait the reaction of the user to this alert (or may not even call bFunction at all, depending on the answer of the user).

Thanks for any kind of advice in advanced.

UPDATE

So as GoZoner suggested, I tried to block the execution in the init() method with dispatch_semaphore_create() / signal() / wait(), but in this case the application is blocked and can't show the AlertView.

Upvotes: 0

Views: 1068

Answers (3)

leonardo
leonardo

Reputation: 1714

You could post an NSNotification from the Closure NSNotificationCenter.defaultCenter().postNotificationName("weirdKeyName", object: nil)

And listen to that notification and call your alert or whatever you need to do when the Closure code has been executed as soon as the notification arrives: NSNotificationCenter.defaultCenter().addObserver(self, selector: "alertFunction", name: "weirdKeyName, object: nil)

alertFunction() {
  ...
}

Waiting for the NSNotification to trigger your alert will not cause your application to block and wait for the closure to complete.

Also if you desire so, you could send the notification to the background thread with NSNotificationQueue

Upvotes: 1

Alex Brown
Alex Brown

Reputation: 42872

Have you considered that your code

SomeSingletonClass.sharedInstance.bFunction()

Might be able to live in a thread other than the main thread?

That way the sharedInstance function (which initialises a SomeSingletonClass) can request the main thread asynchronously create an initialised value, and semaphore wait on it's completion?

That way, you don't block the main thread.

Upvotes: 0

GoZoner
GoZoner

Reputation: 70135

The init() method for your SomeSingletonClass will need to block its execution until the 'Grant Access Authorization Alert' completes. Upon completion, the init() method resumes, the sharedInstance property returns and the bFunction() method is applied to the returned instance.

There are a number of ways to block the execution; what you use will depend on multiprocessing details of your application.

Upvotes: 1

Related Questions