Created
April 29, 2021 11:06
-
-
Save ollieatkinson/4bb17450e2cc582132448f0b1ddec58a to your computer and use it in GitHub Desktop.
Useful extensions for Combine Publisher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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