Clicky

iOS Dev Nugget 297 Defensive Checks for Asynchronous Calls

.

Need to run a code review on your codebase? Hire me

This is a common pattern:

let someModel = getCurrentModel()
functionThatIsAsynchronousEspeciallyAWebAPICall(model: someModel) { result in
    doSomething(with: result)
}

functionThatIsAsynchronousEspeciallyAWebAPICall() is a function that is asynchronous and sometimes takes a few seconds or more to complete and call its completion handler.

In an app that has user accounts or something similar, this becomes:

let account = getAccount()
functionThatIsAsynchronousEspeciallyAWebAPICall(account: account) { result in
    doSomething(with: result)
}

Depending on how you implement doSomething(with:), this might not always behalf correctly because by the time the completion handler is called, the user might have switched accounts. It's better to include a check that the current account is still the same.

let account = getAccount()
functionThatIsAsynchronousEspeciallyAWebAPICall(account: account) { result in
    let currentAccount = getAccount()
    guard currentAccount.username == account.username else { return }
    doSomething(with: result)
}

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues