Skip to content

Instantly share code, notes, and snippets.

@yosshi4486
Last active March 22, 2020 07:37
Show Gist options
  • Save yosshi4486/5d0b2b518226af7b34acf3afedf4ea95 to your computer and use it in GitHub Desktop.
Save yosshi4486/5d0b2b518226af7b34acf3afedf4ea95 to your computer and use it in GitHub Desktop.
Make custom operator without subscription for Combine.
import Combine
public struct Double<Upstream,Output>: Publisher where Upstream:Publisher, Output : Numeric, Upstream.Output == Output {
public typealias Failure = Upstream.Failure
/// The upstream publisher.
public let upstream: Upstream
public init(upstream: Upstream) {
self.upstream = upstream
}
public func receive<S>(subscriber: S) where S:Subscriber, S.Input==Output, S.Failure==Failure {
self.upstream
.map { $0 * 2 }
.subscribe(subscriber)
}
}
public struct Triple<Upstream,Output>: Publisher where Upstream:Publisher, Output : Numeric, Upstream.Output == Output {
public typealias Failure = Upstream.Failure
/// The upstream publisher.
public let upstream: Upstream
public init(upstream: Upstream) {
self.upstream = upstream
}
public func receive<S>(subscriber: S) where S:Subscriber, S.Input==Output, S.Failure==Failure {
self.upstream
.map { $0 * 3 }
.subscribe(subscriber)
}
}
extension Publisher where Output : Numeric {
func double() -> Double<Self, Output> {
.init(upstream: self)
}
func triple() -> Triple<Self, Output> {
.init(upstream: self)
}
}
[1, 2, 3]
.publisher
.double()
.triple()
.sink { print($0) }
// print: 6
// print: 12
// print: 18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment