Skip to content

Instantly share code, notes, and snippets.

@atetlaw
Created January 20, 2022 06:53
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 atetlaw/c92878f4a45ba460ed17485162bb79d1 to your computer and use it in GitHub Desktop.
Save atetlaw/c92878f4a45ba460ed17485162bb79d1 to your computer and use it in GitHub Desktop.
A handy Combine operator if you are only interested in a publisher completing: `MapVoid`
import Combine
extension Publisher {
func mapVoid() -> MapVoid<Self> {
MapVoid(upstream: self)
}
}
struct MapVoid<P: Publisher>: Publisher {
typealias Output = Void
typealias Failure = Never
let upstream: Publishers.ReplaceError<Publishers.Map<P, Void>>
init(upstream: P) {
self.upstream = upstream
.map { _ in () } // map all values to Void
.replaceError(with: ()) // replace all errors with Void
}
public func receive<S>(subscriber: S) where S : Subscriber, S.Input == Void, S.Failure == Never {
upstream.receive(subscriber: subscriber)
}
}
@atetlaw
Copy link
Author

atetlaw commented Jan 20, 2022

Turns a publisher into: Publisher<Void, Never>. Useful if you're combining multiple publishers and only care to know when they're complete. Especially if you're flat mapping multiple publishers with different output and failure types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment