Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A share-based approach to Publisher.prefixInclusive.
import CombineExt
extension Publisher {
func prefixInclusive(while predicate: @escaping (Output) -> Bool) -> AnyPublisher<Output, Failure> {
let shared = share(replay: 1)
return shared
.prefix(while: predicate)
.append(shared.first { !predicate($0) }) // We miiight be able to use the non-predicate `first`
// operator — instead of `first(where:)` — since `append` subscribes to the provided publisher
// only after upstream completes, which in our case loads a `predicate`-failing value to
// `shared`’s internal buffer. If you‘re a thread-safety wizard who can chime in here, please do!
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment