Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Scaffolding for Publisher.prefixInclusive’s two cases.
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)
} 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() // ❌ “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