Skip to content

Instantly share code, notes, and snippets.

@marksands
Created February 24, 2020 02:50
Show Gist options
  • Save marksands/c51517aac83dc470f02f8dc63202e488 to your computer and use it in GitHub Desktop.
Save marksands/c51517aac83dc470f02f8dc63202e488 to your computer and use it in GitHub Desktop.
struct PerformActionSideEffect<Output, Failure: Error> {
private let publisher: AnyPublisher<Output, Failure>
init<P: Publisher>(_ publisher: P) where P.Output == Output, P.Failure == Failure {
self.publisher = publisher.eraseToAnyPublisher()
}
@discardableResult
func performSink(_ action: @escaping (Output) -> Void) -> PerformActionSideEffect {
publisher.subscribe(
Subscribers.Sink(receiveCompletion: { _ in }, receiveValue: action)
)
return PerformActionSideEffect(publisher)
}
@discardableResult
func performAction(_ action: @escaping () -> Void) -> PerformActionSideEffect {
performSink { _ in action() }
}
}
extension Publisher {
@discardableResult
func performSink(_ action: @escaping (Output) -> Void) -> PerformActionSideEffect<Output, Failure> {
return PerformActionSideEffect(self).performSink(action)
}
@discardableResult
func performAction(_ action: @escaping () -> Void) -> PerformActionSideEffect<Output, Failure> {
PerformActionSideEffect(self).performAction(action)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment