Created
November 17, 2020 15:02
-
-
Save joeltrew/3566ba11666be1806fe67f9d8cca13bb to your computer and use it in GitHub Desktop.
Extension that adds a specialised sink method for handling a result enum, providing a failure and success closure avoids a layer of nesting
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
public extension Publisher where Failure == Never { | |
func sinkResult<U, E>( | |
receiveSuccess: @escaping ((U) -> Void), | |
receiveFailure: @escaping ((E) -> Void) | |
) -> AnyCancellable where Output == Result<U, E> { | |
let subscriber = Subscribers.Sink<Output, Failure>( | |
receiveCompletion: { _ in }, | |
receiveValue: { result in | |
switch result { | |
case .success(let value): | |
receiveSuccess(value) | |
case .failure(let failure): | |
receiveFailure(failure) | |
} | |
} | |
) | |
subscribe(subscriber) | |
return AnyCancellable(subscriber) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment