Created
December 2, 2016 07:31
-
-
Save jverkoey/1fbe9369b75f4113785735db893c12d4 to your computer and use it in GitHub Desktop.
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
| public class MaterialRestableStream<T>: MaterialStream<T> { | |
| public var atRest = true { | |
| didSet { | |
| if atRest != oldValue { | |
| for listener in listeners { | |
| (listener as! AnyObserver<Bool>).next(atRest) | |
| } | |
| } | |
| } | |
| } | |
| public func subscribeAtRest(_ next: @escaping (Bool) -> Void) -> Subscription { | |
| let strongStream: MaterialStream<Bool> | |
| if let stream = weakAtRestStream { | |
| strongStream = stream | |
| } else { | |
| strongStream = MaterialStream<Bool>(named: "atRest") { observer in | |
| observer.next(self.atRest) // Give the current state. | |
| self.listeners.add(observer) | |
| return Subscription { | |
| self.listeners.remove(observer) | |
| } | |
| } | |
| // Store the weak reference after storing to a strong reference, | |
| // otherwise the weak stream will be released on assignment. | |
| weakAtRestStream = strongStream | |
| } | |
| return strongStream.subscribe(next: next) | |
| } | |
| // atRestStream indirectly holds a strong reference to self, | |
| // so we keep a weak reference here to avoid a retain cycle. | |
| private weak var weakAtRestStream: (MaterialStream<Bool>)? | |
| private var listeners = NSMutableOrderedSet() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment