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