Skip to content

Instantly share code, notes, and snippets.

@joeltrew
Created November 17, 2020 15:02
Show Gist options
  • Save joeltrew/3566ba11666be1806fe67f9d8cca13bb to your computer and use it in GitHub Desktop.
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
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