Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active January 18, 2021 01:37
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/9b89edfd8ee1b64f4a144768ab4c00a3 to your computer and use it in GitHub Desktop.
Save jasdev/9b89edfd8ee1b64f4a144768ab4c00a3 to your computer and use it in GitHub Desktop.
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