Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Created February 17, 2017 17:00
Show Gist options
  • Save ricardopereira/8738be10ae9063285ae4e9707e133e0b to your computer and use it in GitHub Desktop.
Save ricardopereira/8738be10ae9063285ae4e9707e133e0b to your computer and use it in GitHub Desktop.
class NotificationToken {
let token: NSObjectProtocol
let center: NSNotificationCenter
init(token: NSObjectProtocol, center: NSNotificationCenter) {
self.token = token
self.center = center
}
deinit {
center.removeObserver(token)
}
}
protocol CustomNotification: RawRepresentable {
func notify(center: NSNotificationCenter)
func notify<A>(center: NSNotificationCenter, with object: A)
func addObserver<A>(center: NSNotificationCenter, using block: (A) -> Void) -> NotificationToken
}
final class NotificationBox<T> {
let value: T
init(_ value: T) {
self.value = value
}
}
extension CustomNotification where Self.RawValue == String {
func notify(center: NSNotificationCenter = .defaultCenter()) {
let notification = NSNotification(name: self.rawValue, object: nil)
dispatch_async(dispatch_get_main_queue()) {
center.postNotification(notification)
}
}
func notify<A>(center: NSNotificationCenter = .defaultCenter(), with object: A) {
let notification = NSNotification(name: self.rawValue, object: NotificationBox(object))
dispatch_async(dispatch_get_main_queue()) {
center.postNotification(notification)
}
}
func addObserver<A>(center: NSNotificationCenter = .defaultCenter(), using block: (A) -> Void) -> NotificationToken {
let token = center.addObserverForName(self.rawValue, object: nil, queue: nil, usingBlock: { notification in
if let boxedObject = notification.object as? NotificationBox<A> {
block(boxedObject.value)
}
})
return NotificationToken(token: token, center: center)
}
}
enum AccountNotification: String, CustomNotification {
case Cards
case TaxEstimate
}
@ricardopereira
Copy link
Author

Usage:

// Refresh automatically
cardNotificationToken = AccountNotification.Cards.addObserver { [weak self] (cards: [Card]) in
    // Assuming the default card is the first one
    self?.configure(with: cards.first)
}
AccountNotification.Cards.requestUpdate()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment