Created
February 17, 2017 17:00
-
-
Save ricardopereira/8738be10ae9063285ae4e9707e133e0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: