What is PassthroughSubject & CurrentValueSubject

Nasir picture Nasir · Mar 2, 2020 · Viewed 9.6k times · Source

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?

Answer

donnywals picture donnywals · Mar 6, 2020

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.