Skip to content

Instantly share code, notes, and snippets.

@iThinker
Created November 1, 2016 00:44
Show Gist options
  • Save iThinker/85c11d66f05f9c65dc9c2e8e704a7594 to your computer and use it in GitHub Desktop.
Save iThinker/85c11d66f05f9c65dc9c2e8e704a7594 to your computer and use it in GitHub Desktop.
Observable V2
import Foundation
protocol Observable: class {
associatedtype ObservableAction
typealias SubscriptionBlock = (ObservableAction) -> Void
var subscriptions: NSMapTable<AnyObject, AnyObject> { get set }
func notifyObservers(_ action: ObservableAction) -> Void
func addObserver(_ observer: AnyObject, block: SubscriptionBlock) -> Void
func removeObserver(_ observer: AnyObject) -> Void
}
extension Observable {
func notifyObservers(_ action: ObservableAction) -> Void {
let enumerator = self.subscriptions.objectEnumerator()
while let value = enumerator?.nextObject() {
let subsriptionBlock = value as! SubscriptionBlock
subsriptionBlock(action)
}
}
func addObserver(_ observer: AnyObject, block: SubscriptionBlock) -> Void {
self.subscriptions.setObject(block as AnyObject?, forKey: observer)
}
func removeObserver(_ observer: AnyObject) -> Void {
self.subscriptions.removeObject(forKey: observer)
}
}
enum TestObservableActions {
case testAction
}
class TestObservable: Observable {
internal var subscriptions: NSMapTable<AnyObject, AnyObject> = NSMapTable.weakToWeakObjects()
typealias ObservableAction = TestObservableActions
func testFunc() -> Void {
self.notifyObservers(.testAction)
}
}
class TestObserver {
internal func observe(_ action: TestObservableActions) {
print("Action: \(action)")
}
}
func test() -> Void {
let testObservable = TestObservable()
let testObserver = TestObserver()
testObservable.addObserver(testObserver, block: testObserver.observe)
testObservable.testFunc()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment