Created
June 5, 2020 23:33
-
-
Save coybit/8745f0529202c5af0b5f67c0f2c65892 to your computer and use it in GitHub Desktop.
Two simple Combine Operators to test the sequence of values a Combine Publisher emits.
This file contains hidden or 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
| // Operators | |
| extension Publisher where Self.Output: Equatable { | |
| public func test(equalTo expectation: [Self.Output]) -> AnyCancellable { | |
| self | |
| .assertNoFailure() | |
| .reduce([Self.Output](), { $0 + [$1] }) | |
| .sink() { assert($0 == expectation) } | |
| } | |
| public func test(first: Int, equalTo expectation: [Self.Output]) -> AnyCancellable { | |
| self | |
| .assertNoFailure() | |
| .prefix(first) | |
| .reduce([Self.Output](), { $0 + [$1] }) | |
| .sink() { assert($0 == expectation) } | |
| } | |
| } | |
| // Sample Code | |
| enum State: Equatable { | |
| case idle | |
| case loading | |
| case loaded | |
| case error | |
| } | |
| struct ViewModel { | |
| let state = CurrentValueSubject<State, Never>(.idle) | |
| func viewDidLoad() { | |
| state.value = .loading | |
| // Loading data ... | |
| state.value = .loaded | |
| } | |
| func viewDidUnload() { | |
| state.send(completion: .finished) | |
| } | |
| } | |
| // Sample Tests | |
| let vm = ViewModel() | |
| vm.state.test(equalTo: [.idle, .loading, .loaded]).store(in: &cancellables) | |
| vm.state.test(first: 2, equalTo: [.idle, .loading]).store(in: &cancellables) | |
| vm.viewDidLoad() | |
| vm.viewDidUnload() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment