Last active
April 27, 2023 09:49
-
-
Save woodycatliu/347a06d5e23783f8764c04ab97163694 to your computer and use it in GitHub Desktop.
Encapsulates PassthroughSubject / CurrentValueSubject
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
/// 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 | |
} | |
} | |
} | |
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 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