Last active
May 26, 2016 21:16
-
-
Save zats/1ecbb2427862fb5d526f945ac6f74664 to your computer and use it in GitHub Desktop.
PubSub protocol
This file contains 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
protocol PubSubMessageType { | |
associatedtype Topic | |
var topic: Topic { get } | |
} | |
protocol PubSubType { | |
associatedtype Message = PubSubMessageType | |
associatedtype Topic | |
associatedtype Handler = Message -> Void | |
associatedtype Unsubscribe = Void -> Void | |
func send(message: Message) | |
func subscribe(topic: Topic, handler: Handler) -> Unsubscribe | |
} | |
extension PubSubType { | |
func subscribeOnce(fn: (Topic, Handler) -> Unsubscribe) -> (Topic, Handler) -> Void { | |
return { topic, handler in | |
var unsubscribe: Unsubscribe? | |
let myHandler: Handler = { // cannot convert value of type '(_) -> ()' to specified type 'Self.Handler' | |
unsubscribe?() | |
handler($0) | |
} | |
unsubscribe = fn(topic, myHandler) | |
} | |
} | |
} | |
// Usage | |
let p = PubSub<Message, String>() | |
let _ = p.subscribe("topic") { | |
print($0) // will print "topic" as many times as it's sent | |
} | |
p.subscribeOnce(p.subscribe)("topic") { | |
print("Once:", $0) // will print "topic" once | |
} | |
p.send(Message(topic: "topic")) | |
p.send(Message(topic: "topic")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment