Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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)")
index += 1
let example = Example()
print("First subscription.")
let subscription1 = example.value.sink { print("sub1: \($0)") }
print("Second subscription.")
let subscription2 = example.value.sink { print("sub2: \($0)") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment