Skip to content

Instantly share code, notes, and snippets.

@peterfriese
Last active March 23, 2022 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterfriese/1b9503b441ab185d72dafcd38b5c034b to your computer and use it in GitHub Desktop.
Save peterfriese/1b9503b441ab185d72dafcd38b5c034b to your computer and use it in GitHub Desktop.
Make it easier to perform side effects (such as toggling a progress view) in a Combine pipeline. See this Twitter conversation for context: https://twitter.com/DonnyWals/status/1506330967941820423
extension Publisher {
/// Performs the specified closures when publisher events occur.
///
/// This is an overloaded version of ``Publisher/handleEvents(receiveSubscription:receiveOutput:receiveCompletion:receiveCancel:receiveRequest:)``
/// that only accepts a closure for the `receiveOutput` events. Use it to inspect events as they pass through the pipeline.
///
/// - Parameters:
/// - receiveOutput: A closure that executes when the publisher receives a value from the upstream publisher.
/// - Returns: A publisher that performs the specified closures when publisher events occur.
func handleEvents(_ receiveOutput: (@escaping (Self.Output) -> Void)) -> Publishers.HandleEvents<Self> {
self.handleEvents(receiveOutput: receiveOutput)
}
/// Performs the specified closures when publisher events occur.
///
/// This is an overloaded version of ``Publisher/handleEvents(receiveSubscription:receiveOutput:receiveCompletion:receiveCancel:receiveRequest:)``
/// that only accepts a closure for the `receiveOutput` events. Use it to execute side effects while events pass down the pipeline.
///
/// - Parameters:
/// - receiveOutput: A closure that executes when the publisher receives a value from the upstream publisher.
/// - Returns: A publisher that performs the specified closures when publisher events occur.
func handleEvents(_ receiveOutput: (@escaping () -> Void)) -> Publishers.HandleEvents<Self> {
self.handleEvents { output in
receiveOutput()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment