Created
February 5, 2021 16:00
-
-
Save HarshilShah/c31d414d2b68f939de214201b44402b2 to your computer and use it in GitHub Desktop.
A ReactiveSwift.Property equivalent in Combine
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
| import Combine | |
| import Foundation | |
| final class Property<Value> { | |
| // MARK: Public properties | |
| var value: Value { subject.value } | |
| // MARK: Private properties | |
| private var subject: CurrentValueSubject<Value, Never> | |
| private var cancellable: AnyCancellable? | |
| // MARK: Initializers | |
| init<P: Publisher>( | |
| initialValue: Value, then publisher: P | |
| ) where P.Output == Value, P.Failure == Never { | |
| self.subject = CurrentValueSubject(initialValue) | |
| self.cancellable = publisher.subscribe(subject) | |
| } | |
| } | |
| extension Property: Publisher { | |
| typealias Output = Value | |
| typealias Failure = Never | |
| func receive<S>(subscriber: S) where S: Subscriber, S.Input == Output, S.Failure == Failure { | |
| subject.receive(subscriber: subscriber) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment