Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active April 27, 2023 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/347a06d5e23783f8764c04ab97163694 to your computer and use it in GitHub Desktop.
Save woodycatliu/347a06d5e23783f8764c04ab97163694 to your computer and use it in GitHub Desktop.
Encapsulates PassthroughSubject / CurrentValueSubject
/// Property Wrapper that wraps an `AnyPublisher`, which is backed by a `CurrentValueSubject`. This is to make it possible to easily expose just a publisher to consumers of a type,
/// without also exposing the `CurrentValueSubject` to consumers, effectively allowing for public reads and private writes of a publisher.
@propertyWrapper
struct CurrentValueBacked<Output> {
private var subject: CurrentValueSubject<Output, Never>
init(_ output: Output) {
subject = CurrentValueSubject<Output, Never>(output)
}
var wrappedValue: AnyPublisher<Output, Never> {
subject.eraseToAnyPublisher()
}
var projectedValue: CurrentValueBacked<Output> {
self
}
func send(_ value: Output) {
subject.send(value)
}
}
extension CurrentValueBacked where Output == Void {
func send(_ output: Output) {
subject.send(output)
}
var value: Output {
get {
return subject.value
}
set {
subject.value = newValue
}
}
}
import Foundation
import Combine
@propertyWrapper
struct PassthroughBacked<Output> {
private var subject: PassthroughSubject<Output, Never>
init() {
subject = PassthroughSubject<Output, Never>()
}
var wrappedValue: AnyPublisher<Output, Never> {
subject.eraseToAnyPublisher()
}
var projectedValue: PassthroughBacked<Output> {
self
}
func send(_ value: Output) {
subject.send(value)
}
}
extension PassthroughBacked where Output == Void {
func send() {
subject.send()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment