Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a promise that's abandoned?

I have the following code defined in a view controller.

    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }

getAccount makes a REST API request.

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

like image 581
Ian Warburton Avatar asked Apr 01 '17 16:04

Ian Warburton


1 Answers

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

Yes, it does still run.

Be forewarned that the reference to self in the closure means that it is also keeping a reference to the view controller until that then closure finishes running. For that reason, if there's a chance the view controller could have been dismissed, you might want to use a weak reference:

_ = accountService.getAccount().then { [weak self] user -> Void in
    self?.txtBxUser.text = user.username
    self?.txtBxEmail.text = user.email
}

Ideally, you should also make getAccount cancellable and cancel it in the view controller's deinit.

(Note, in FAQ - Should I be Concerned About Retain Cycles, the PromiseKit documentation points out that you don't need weak references, which is correct. It's just a question of whether or not you mind if the deallocation of the dismissed view controller is deferred until after the promise is fulfilled.)

like image 72
Rob Avatar answered Oct 10 '22 19:10

Rob