Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created April 29, 2021 11:06
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 ollieatkinson/4bb17450e2cc582132448f0b1ddec58a to your computer and use it in GitHub Desktop.
Save ollieatkinson/4bb17450e2cc582132448f0b1ddec58a to your computer and use it in GitHub Desktop.
Useful extensions for Combine Publisher
extension Publisher where Failure == Never {
public func sink<Root>(to handler: @escaping (Root) -> (Output) -> Void, on root: Root) -> AnyCancellable where Root: AnyObject {
sink{ [weak root] value in
guard let root = root else { return }
handler(root)(value)
}
}
public func sink<Root>(to handler: @escaping (Root) -> () -> Void, on root: Root) -> AnyCancellable where Root: AnyObject {
sink{ [weak root] _ in
guard let root = root else { return }
handler(root)()
}
}
}
extension Publisher {
public func eraseToAnyError() -> Publishers.MapError<Self, Error> {
mapError { $0 as Error }
}
public func `catch`(_ handler: @escaping (Failure) -> Output) -> Publishers.Catch<Self, Just<Output>> {
`catch`{ error in Just(handler(error)) }
}
public func flatMap<P>(
maxPublishers: Subscribers.Demand = .unlimited,
_ transform: @escaping (Output) -> P
) -> Publishers.FlatMap<Publishers.MapError<P, Error>, Publishers.MapError<Self, Error>> where P: Publisher {
eraseToAnyError().flatMap { output in
transform(output).eraseToAnyError()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment