Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created October 19, 2020 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaSullivan/0985e00b9828a70d25383fadb4cbf013 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/0985e00b9828a70d25383fadb4cbf013 to your computer and use it in GitHub Desktop.
An example of how to create CurrentValueSubject behavior without needing to set an initial value.
import Foundation
import Combine
class Example {
private var index = 1
private let valuePublisher = CurrentValueSubject<Int?, Never>(nil)
var value: AnyPublisher<Int, Never> {
valuePublisher.compactMap({ $0 }).eraseToAnyPublisher()
}
func doSomething() {
print("[Example] sending value: \(index)")
valuePublisher.send(index)
index += 1
}
}
let example = Example()
print("First subscription.")
let subscription1 = example.value.sink { print("sub1: \($0)") }
example.doSomething()
print("Second subscription.")
let subscription2 = example.value.sink { print("sub2: \($0)") }
example.doSomething()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment