Search code examples
swiftswift5

Callback functions or Post notifications


I am currently working on a login functionality and came up with two different ways I can continue moving forward once receiving a response. The first way is to use a callback function and return the result back up the chain. The other is to post a notification and let the class that needs this response to observe and wait. Which one would you recommend and why? Please note I would be using this same approach for future HTTP calls using the AlamoFire library, I am trying to be mindful of multiple threads being created and avoiding any unnecessary memory usage. I believe a callback would meet these requirements, however, I want to see everybody's opinion on this! Thank you in advance!

//Code sample from AlamoFire:

AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)

    //Post notification?
    //use callback?
}

Solution

  • Post notifications are for important events inside your application, not for every network call. For example "user logged in" can be (in certain cases) a right candidate for notification, since it's an application-wide event, that could be interesting to multiple observers.

    Why not use notifications in all functions? In short - because they are a broadcast. So why tell the whole app that some function has a result of some network request, when probably only one class cares about it? You can also read this post, which discusses other reasons not to use it (they are around UI use cases, but it also applies to your use case).

    But callbacks are not the only option either. They are good if you have interaction between 2 parties only, and usually they work best for simple things, that do not involve elaborate logic, or a lot of code (google "swift callback hell" to see some examples of when NOT to use callbacks). There are 2 more options:

    1. Observer pattern (which is used by notifications) can also be implemented more elegantly with protocol and subscription. See the full idea here. In this case you can notify multiple classes (just like with notifications), but you only notify those interested in the result.
    2. Promises, although not as native to Swift as to JS, but still becoming quite popular. You can see an example here