Created
January 17, 2021 16:54
-
-
Save sssbohdan/4cfc0d7156c1f5b93baf95d0a3e02c98 to your computer and use it in GitHub Desktop.
ObserverExample
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 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