Last active
August 29, 2015 14:24
-
-
Save hartbit/5a40761d8851598b064c to your computer and use it in GitHub Desktop.
Publisher/Subscriber Pattern from C# to Swift
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
using System.Collections.Generic; | |
interface IPublisher<T> { | |
void Subscribe(ISubscriber<T> subscriber); | |
} | |
interface ISubscriber<T> { | |
void Publish(T value); | |
} | |
class Subject<T>: IPublisher<T>, ISubscriber<T> { | |
private List<ISubscriber<T>> subscribers = new List<ISubscriber<T>>(); | |
public void Subscribe(ISubscriber<T> subscriber) { | |
this.subscribers.Add(subscriber); | |
} | |
public void Publish(T value) { | |
foreach (var subscriber in this.subscribers) { | |
subscriber.Publish(value); | |
} | |
} | |
} |
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
protocol SubscriberType { | |
typealias Element | |
func publish(value: Element) | |
} | |
protocol PublisherType { | |
typealias Element | |
func subscribe<S: SubscriberType where S.Element == Element>(subscriber: S) | |
} | |
class Subject<T>: SubscriberType, PublisherType { | |
typealias Element = T | |
// Can't define a list of any subscribers of T | |
private var subscribers: [SubscriberType] = [] | |
func subscribe<S : SubscriberType where S.Element == Element>(subscriber: S) { | |
subscribers.append(subscriber) | |
} | |
func publish(value: T) { | |
for subscriber in subscribers { | |
subscriber.publish(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment