Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active November 17, 2021 00:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fxm90/fcb2eb9d92655889d549e7f57168a0fb to your computer and use it in GitHub Desktop.
Save fxm90/fcb2eb9d92655889d549e7f57168a0fb to your computer and use it in GitHub Desktop.
Playground showing the difference between a `PassthroughSubject` and a `CurrentValueSubject`
//
// 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")
@fxm90
Copy link
Author

fxm90 commented Jul 31, 2020

The playground will generate the following output:

1st. Subscriber: One
1st. Subscriber: Two
1st. Subscriber: Three
1st. Subscriber: Four
2nd. Subscriber: Four
1st. Subscriber: Five
2nd. Subscriber: Five

 -- -- -- -- -- -- --

1st. Subscriber: Zero (initial value)
1st. Subscriber: One
1st. Subscriber: Two
1st. Subscriber: Three
2nd. Subscriber: Three
1st. Subscriber: Four
2nd. Subscriber: Four
1st. Subscriber: Five
2nd. Subscriber: Five

@fxm90
Copy link
Author

fxm90 commented Jul 31, 2020

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