Skip to content

Instantly share code, notes, and snippets.

@mikezs
Created October 22, 2020 09:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikezs/f1bcea1fa25a21d6a1ddce18f047e1bf to your computer and use it in GitHub Desktop.
Save mikezs/f1bcea1fa25a21d6a1ddce18f047e1bf to your computer and use it in GitHub Desktop.
Publisher+PromiseExtension.swift
extension Publisher {
func and<T: Publisher>(_ closure: @escaping (Output) -> T) -> AnyPublisher<(Output, T.Output), Failure> where T.Failure == Failure {
then { output in
Just(output)
.setFailureType(to: Failure.self)
.zip(closure(output))
.eraseToAnyPublisher()
}
}
func then<T: Publisher>(_ closure: @escaping (Output) -> T) -> AnyPublisher<T.Output, Failure> where T.Failure == Failure {
flatMap { output in
closure(output)
}
.eraseToAnyPublisher()
}
func done(_ closure: @escaping (Output) -> Void, assertIfNotOnMainQueue: Bool = true) -> AnyPublisher<Output, Failure> {
flatMap { output -> AnyPublisher<Output, Failure> in
assert(!(assertIfNotOnMainQueue && !Thread.isMainThread),
"""
done() is not being called on the main thread, this is probably not right. \
If you meant this to happen call with assertIfNotOnMainQueue: false
""")
closure(output)
return eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func fail(_ closure: @escaping (Failure) -> Void, assertIfNotOnMainQueue: Bool = true) -> AnyPublisher<Output, Failure> {
self.catch { error -> AnyPublisher<Output, Failure> in
assert(!(assertIfNotOnMainQueue && !Thread.isMainThread),
"""
fail() is not being called on the main thread, this is probably not right. \
If you meant this to happen call with assertIfNotOnMainQueue: false
""")
closure(error)
return eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func always(_ closure: @escaping (Result<Output, Failure>) -> Void, assertIfNotOnMainQueue: Bool = true) -> Cancellable {
return sink { completion in
switch completion {
case .finished:
break
case let .failure(error):
assert(!(assertIfNotOnMainQueue && !Thread.isMainThread),
"""
always() is not being called on the main thread, this is probably not right. \
If you meant this to happen call with assertIfNotOnMainQueue: false
""")
closure(.failure(error))
}
} receiveValue: { output in
assert(!(assertIfNotOnMainQueue && !Thread.isMainThread),
"""
always() is not being called on the main thread, this is probably not right. \
If you meant this to happen call with assertIfNotOnMainQueue: false
""")
closure(.success(output))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment