Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active January 17, 2021 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/9ef546fd9f535f043ab539128c93ff98 to your computer and use it in GitHub Desktop.
Save jasdev/9ef546fd9f535f043ab539128c93ff98 to your computer and use it in GitHub Desktop.
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)
.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