Created
October 22, 2020 09:46
-
-
Save mikezs/f1bcea1fa25a21d6a1ddce18f047e1bf to your computer and use it in GitHub Desktop.
Publisher+PromiseExtension.swift
This file contains hidden or 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 { | |
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