Skip to content

Instantly share code, notes, and snippets.

@zats
Last active May 26, 2016 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zats/1ecbb2427862fb5d526f945ac6f74664 to your computer and use it in GitHub Desktop.
Save zats/1ecbb2427862fb5d526f945ac6f74664 to your computer and use it in GitHub Desktop.
PubSub protocol
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