I happen to look into Apple's new Combine framework, where I see two things
PassthroughSubject<String, Failure>
CurrentValueSubject<String, Failure>
Can someone explain to me what is meaning & use of them?
Use eraseToAnyPublisher() to expose an instance of AnyPublisher to the downstream subscriber, rather than this publisher's actual type. This form of type erasure preserves abstraction across API boundaries, such as different modules.
Overview. The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.
Swift Publisher is a super-intuitive, all-purpose page layout and desktop publishing app for Mac. It doesn't matter what kind of document you need to layout and print — from brochures and calendars to CD labels and eye-catching, professional business cards — Swift Publisher covers it all.
I think we can make analogies with real world cases.
PassthroughSubject = A doorbell push button
When someone rings the door, you are notified only if you are at home (you are the subscriber)
PassthroughSubject doesn't have a state, it emits whatever it receives to its subscribers.
CurrentValueSubject = A light switch Someone turns on the lights in your home when you are outside. You get back home and you know someone has turned them on.
CurrentValueSubject has an initial state, it retains the data you put in as its state.
Both PassthroughSubject
and CurrentValueSubject
are publishers that conform to the Subject
protocol which means you can call send
on them to push new values downstream at will.
The main difference is that CurrentValueSubject
has a sense of state (current value) and PassthroughSubject
simply relays values directly to its subscribers without remembering the "current" value:
var current = CurrentValueSubject<Int, Never>(10) var passthrough = PassthroughSubject<Int, Never>() current.send(1) passthrough.send(1) current.sink(receiveValue: { print($0) }) passthrough.sink(receiveValue: { print($0) })
You'd see that the current.sink
is called immediately with 1
. The passthrough.sink
is not called because it has no current value. The sink will only be called for values that are emitted after you subscribe.
Note that you can also get and set the current value of a CurrentValueSubject
using its value
property:
current.value // 1 current.value = 5 // equivalent to current.send(5)
This isn't possible for a passthrough subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With