Last active
January 17, 2021 23:47
-
-
Save jasdev/9ef546fd9f535f043ab539128c93ff98 to your computer and use it in GitHub Desktop.
Scaffolding for Publisher.prefixInclusive’s two cases.
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
extension Publisher { | |
func prefixInclusive(while predicate: @escaping (Output) -> Bool) -> AnyPublisher<Output, Failure> { | |
flatMap { value -> AnyPublisher<PrefixInclusiveEvent<Output>, Failure> in | |
if predicate(value) { | |
return Just(.predicatePassingValueOrIncluded(value)) | |
.setFailureType(to: Failure.self) | |
.eraseToAnyPublisher() | |
} else { | |
return [.predicatePassingValueOrIncluded(value), .end] | |
.publisher // (1) `Sequence.publisher` is a hidden gem for converting an ordinary sequence | |
// into a publisher of elements, followed by a completion when the underlying iterator `nil`s out. | |
.setFailureType(to: Failure.self) // (2) We’ll tidy up the `setFailureType`-`eraseToAnyPublisher` dance | |
// we have to do in each clause. | |
.eraseToAnyPublisher() | |
} | |
} | |
.eraseToAnyPublisher() // ❌ “Type of expression is ambiguous without more context.” | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment