Last active
November 17, 2021 00:51
Playground showing the difference between a `PassthroughSubject` and a `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
// | |
// Combine-PassthroughSubject-CurrentValueSubject.playground | |
// | |
// Created by Felix Mau on 30.07.20. | |
// Copyright © 2020 Felix Mau. All rights reserved. | |
// | |
import PlaygroundSupport | |
import Combine | |
var subscriptions = Set<AnyCancellable>() | |
// MARK: - PassthroughSubject | |
/// After subscribing to a `PassthroughSubject` you'll get all the **upcoming elements**. | |
let passthroughSubject = PassthroughSubject<String, Never>() | |
passthroughSubject | |
.sink(receiveValue: { value in | |
print("1st. Subscriber:", value) | |
}) | |
.store(in: &subscriptions) | |
passthroughSubject.send("One") | |
passthroughSubject.send("Two") | |
passthroughSubject.send("Three") | |
passthroughSubject | |
.sink(receiveValue: { value in | |
print("2nd. Subscriber:", value) | |
}) | |
.store(in: &subscriptions) | |
passthroughSubject.send("Four") | |
passthroughSubject.send("Five") | |
print("\n", "-- -- -- -- -- -- --", "\n") | |
// MARK: - CurrentValueSubject | |
/// After subscribing to a `PassthroughSubject` you'll receive the **most recent element**, as well as all the **upcoming elements**. | |
/// Therefore a `CurrentValueSubject` needs an initial value! | |
let currentValueSubject = CurrentValueSubject<String, Never>("Zero (initial value)") | |
currentValueSubject | |
.sink(receiveValue: { value in | |
print("1st. Subscriber:", value) | |
}) | |
.store(in: &subscriptions) | |
currentValueSubject.send("One") | |
currentValueSubject.send("Two") | |
currentValueSubject.send("Three") | |
currentValueSubject | |
.sink(receiveValue: { value in | |
print("2nd. Subscriber:", value) | |
}) | |
.store(in: &subscriptions) | |
currentValueSubject.send("Four") | |
currentValueSubject.send("Five") |
The second subscriber to the PassthroughSubject
will only receive "Four" and "Five" (all upcoming values after the subscription).
The second subscriber to the CurrentValueSubject
will receive "Three", "Four" and "Five" (the current value and all upcoming values of the subscription).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The playground will generate the following output: