-
-
Save amine2233/b57e02b69b1d73eafb22d7acc9dbe5f2 to your computer and use it in GitHub Desktop.
An example implementation of @published from Swift's Combine framework along with an "immutable" variant.
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
import Combine | |
/** | |
An observable, mutable property. | |
Replays the current value when subscribed. | |
*/ | |
@propertyWrapper | |
struct Published<Output>: Publisher { | |
typealias Failure = Never | |
private let subject: CurrentValueSubject<Output, Never> | |
var value: Output { | |
get { subject.value } | |
nonmutating set { subject.value = newValue } | |
} | |
init(initialValue: Output) { | |
subject = CurrentValueSubject<Output, Never>(initialValue) | |
} | |
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { | |
subject.receive(subscriber: subscriber) | |
} | |
} | |
/** | |
An immutable, observable property. | |
Replays the current value when subscribed. | |
*/ | |
@propertyWrapper | |
struct ImmutablePublished<Output>: Publisher { | |
typealias Failure = Never | |
private let subject: CurrentValueSubject<Output, Failure> | |
var value: Output { subject.value } | |
private let cancellable: Cancellable | |
init(_ publisher: AnyPublisher<Output, Failure>, initialValue: Output) { | |
subject = CurrentValueSubject<Output, Failure>(initialValue) | |
cancellable = publisher.assign(to: \.value, on: subject) | |
} | |
func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { | |
subject.receive(subscriber: subscriber) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment