Skip to content

Instantly share code, notes, and snippets.

@sssbohdan
Created January 17, 2021 16:54
Show Gist options
  • Save sssbohdan/4cfc0d7156c1f5b93baf95d0a3e02c98 to your computer and use it in GitHub Desktop.
Save sssbohdan/4cfc0d7156c1f5b93baf95d0a3e02c98 to your computer and use it in GitHub Desktop.
ObserverExample
protocol ActionDoable: AnyObject {
func doAction(with value: Int)
}
class A: ActionDoable {
func doAction(with value: Int) {
print("do from A \(value)")
}
}
class B: ActionDoable {
func doAction(with value: Int) {
print("do from B \(value)")
}
}
private class Weakifier<T: AnyObject> {
weak var weakObject: T?
init(object: T) {
self.weakObject = object
}
}
final class Subject {
private var actionDoable = [Weakifier<AnyObject>]()
func addObserver(_ observer: ActionDoable) {
self.actionDoable.append(Weakifier(object: observer))
}
func trigger(value: Int) {
self.actionDoable
.compactMap { $0.weakObject as? ActionDoable }
.forEach { $0.doAction(with: value) }
}
}
let subject = Subject()
let a = A()
let b = B()
subject.addObserver(a)
subject.addObserver(b)
subject.trigger(value: 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment