-
-
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.
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
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