Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Combine Generated Interface
import Darwin
/// A type-erasing cancellable object that executes a provided closure when canceled.
///
/// Subscriber implementations can use this type to provide a “cancellation token” that makes it possible for a caller to cancel a publisher, but not to use the ``Subscription`` object to request items.
///
/// An ``AnyCancellable`` instance automatically calls ``Cancellable/cancel()`` when deinitialized.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final public class AnyCancellable : Cancellable, Hashable {
/// Initializes the cancellable object with the given cancel-time closure.
///
/// - Parameter cancel: A closure that the `cancel()` method executes.
public init(_ cancel: @escaping () -> Void)
public init<C>(_ canceller: C) where C : Cancellable
/// Cancel the activity.
final public func cancel()
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: Never call `finalize()` on `hasher`. Doing so may become a
/// compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
final public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: AnyCancellable, rhs: AnyCancellable) -> Bool
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
final public var hashValue: Int { get }
}
extension AnyCancellable {
/// Stores this type-erasing cancellable instance in the specified collection.
///
/// - Parameter collection: The collection in which to store this ``AnyCancellable``.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final public func store<C>(in collection: inout C) where C : RangeReplaceableCollection, C.Element == AnyCancellable
/// Stores this type-erasing cancellable instance in the specified set.
///
/// - Parameter set: The set in which to store this ``AnyCancellable``.
final public func store(in set: inout Set<AnyCancellable>)
}
/// A publisher that performs type erasure by wrapping another publisher.
///
/// ``AnyPublisher`` is a concrete implementation of ``Publisher`` that has no significant properties of its own, and passes through elements and completion values from its upstream publisher.
///
/// Use ``AnyPublisher`` to wrap a publisher whose type has details you don’t want to expose across API boundaries, such as different modules. Wrapping a ``Subject`` with ``AnyPublisher`` also prevents callers from accessing its ``Subject/send(_:)`` method. When you use type erasure this way, you can change the underlying publisher implementation over time without affecting existing clients.
///
/// You can use Combine’s ``Publisher/eraseToAnyPublisher()`` operator to wrap a publisher with ``AnyPublisher``.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnyPublisher<Output, Failure> : CustomStringConvertible, CustomPlaygroundDisplayConvertible where Failure : Error {
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
/// A custom playground description for this instance.
public var playgroundDescription: Any { get }
/// Creates a type-erasing publisher to wrap the provided publisher.
///
/// - Parameter publisher: A publisher to wrap with a type-eraser.
@inlinable public init<P>(_ publisher: P) where Output == P.Output, Failure == P.Failure, P : Publisher
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension AnyPublisher : Publisher {
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
@inlinable public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
}
/// A type-erasing subscriber.
///
/// Use an ``AnySubscriber`` to wrap an existing subscriber whose details you don’t want to expose. You can also use ``AnySubscriber`` to create a custom subscriber by providing closures for the methods defined in ``Subscriber``, rather than implementing ``Subscriber`` directly.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@frozen public struct AnySubscriber<Input, Failure> : Subscriber, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible where Failure : Error {
/// A unique identifier for identifying publisher streams.
public let combineIdentifier: CombineIdentifier
/// A textual representation of this instance.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(describing:)`
/// initializer. This initializer works with any type, and uses the custom
/// `description` property for types that conform to
/// `CustomStringConvertible`:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String { get }
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
public var customMirror: Mirror { get }
/// A custom playground description for this instance.
public var playgroundDescription: Any { get }
/// Creates a type-erasing subscriber to wrap an existing subscriber.
///
/// - Parameter s: The subscriber to type-erase.
@inlinable public init<S>(_ s: S) where Input == S.Input, Failure == S.Failure, S : Subscriber
public init<S>(_ s: S) where Input == S.Output, Failure == S.Failure, S : Subject
/// Creates a type-erasing subscriber that executes the provided closures.
///
/// - Parameters:
/// - receiveSubscription: A closure to execute when the subscriber receives the initial subscription from the publisher.
/// - receiveValue: A closure to execute when the subscriber receives a value from the publisher.
/// - receiveCompletion: A closure to execute when the subscriber receives a completion callback from the publisher.
@inlinable public init(receiveSubscription: ((Subscription) -> Void)? = nil, receiveValue: ((Input) -> Subscribers.Demand)? = nil, receiveCompletion: ((Subscribers.Completion<Failure>) -> Void)? = nil)
/// Tells the subscriber that it has successfully subscribed to the publisher and may request items.
///
/// Use the received ``Subscription`` to request items from the publisher.
/// - Parameter subscription: A subscription that represents the connection between publisher and subscriber.
@inlinable public func receive(subscription: Subscription)
/// Tells the subscriber that the publisher has produced an element.
///
/// - Parameter input: The published element.
/// - Returns: A `Subscribers.Demand` instance indicating how many more elements the subscriber expects to receive.
@inlinable public func receive(_ value: Input) -> Subscribers.Demand
/// Tells the subscriber that the publisher has completed publishing, either normally or with an error.
///
/// - Parameter completion: A ``Subscribers/Completion`` case indicating whether publishing completed normally or with an error.
@inlinable public func receive(completion: Subscribers.Completion<Failure>)
}
/// A protocol indicating that an activity or action supports cancellation.
///
/// Calling ``Cancellable/cancel()`` frees up any allocated resources. It also stops side effects such as timers, network access, or disk I/O.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol Cancellable {
/// Cancel the activity.
func cancel()
}
extension Cancellable {
/// Stores this cancellable instance in the specified collection.
///
/// - Parameter collection: The collection in which to store this ``Cancellable``.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public func store<C>(in collection: inout C) where C : RangeReplaceableCollection, C.Element == AnyCancellable
/// Stores this cancellable instance in the specified set.
///
/// - Parameter set: The set in which to store this ``Cancellable``.
public func store(in set: inout Set<AnyCancellable>)
}
/// A unique identifier for identifying publisher streams.
///
/// To conform to ``CustomCombineIdentifierConvertible`` in a
/// ``Subscription`` or ``Subject`` that you implement as a structure, create an instance of ``CombineIdentifier`` as follows:
///
/// let combineIdentifier = CombineIdentifier()
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct CombineIdentifier : Hashable, CustomStringConvertible {
/// Creates a unique Combine identifier.
public init()
/// Creates a Combine identifier, using the bit pattern of the provided object.
public init(_ obj: AnyObject)
/// A textual representation of this instance.
public var description: String { get }
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
///
/// - Important: `hashValue` is deprecated as a `Hashable` requirement. To
/// conform to `Hashable`, implement the `hash(into:)` requirement instead.
public var hashValue: Int { get }
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: Never call `finalize()` on `hasher`. Doing so may become a
/// compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher)
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: CombineIdentifier, b: CombineIdentifier) -> Bool
}
/// A publisher that provides an explicit means of connecting and canceling publication.
///
/// Use a ``ConnectablePublisher`` when you need to perform additional configuration or setup prior to producing any elements.
///
/// This publisher doesn’t produce any elements until you call its ``ConnectablePublisher/connect()`` method.
///
/// Use ``Publisher/makeConnectable()`` to create a ``ConnectablePublisher`` from any publisher whose failure type is <doc://com.apple.documentation/documentation/Swift/Never>.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol ConnectablePublisher : Publisher {
/// Connects to the publisher, allowing it to produce elements, and returns an instance with which to cancel publishing.
///
/// - Returns: A ``Cancellable`` instance that you use to cancel publishing.
func connect() -> Cancellable
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension ConnectablePublisher {
/// Automates the process of connecting or disconnecting from this connectable publisher.
///
/// Use ``ConnectablePublisher/autoconnect()`` to simplify working with ``ConnectablePublisher`` instances, such as <doc://com.apple.documentation/documentation/Foundation/Timer/TimerPublisher> in the Foundation framework.
///
/// In the following example, the <doc://com.apple.documentation/documentation/Foundation/Timer/3329589-publish> operator creates a <doc://com.apple.documentation/documentation/Foundation/Timer/TimerPublisher>, which is a ``ConnectablePublisher``. As a result, subscribers don’t receive any values until after a call to ``ConnectablePublisher/connect()``.
/// For convenience when working with a single subscriber, the ``ConnectablePublisher/autoconnect()`` operator performs the ``ConnectablePublisher/connect()`` call when attached to by the subscriber.
///
/// cancellable = Timer.publish(every: 1, on: .main, in: .default)
/// .autoconnect()
/// .sink { date in
/// print ("Date now: \(date)")
/// }
/// - Returns: A publisher which automatically connects to its upstream connectable publisher.
public func autoconnect() -> Publishers.Autoconnect<Self>
}
/// A subject that wraps a single value and publishes a new element whenever the value changes.
///
/// Unlike ``PassthroughSubject``, ``CurrentValueSubject`` maintains a buffer of the most recently published element.
///
/// Calling ``CurrentValueSubject/send(_:)`` on a ``CurrentValueSubject`` also updates the current value, making it equivalent to updating the ``CurrentValueSubject/value`` directly.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final public class CurrentValueSubject<Output, Failure> : Subject where Failure : Error {
/// The value wrapped by this subject, published as a new element whenever it changes.
final public var value: Output
/// Creates a current value subject with the given initial value.
///
/// - Parameter value: The initial value to publish.
public init(_ value: Output)
/// Sends a subscription to the subscriber.
///
/// This call provides the ``Subject`` an opportunity to establish demand for any new upstream subscriptions.
///
/// - Parameter subscription: The subscription instance through which the subscriber can request elements.
final public func send(subscription: Subscription)
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
final public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
/// Sends a value to the subscriber.
///
/// - Parameter value: The value to send.
final public func send(_ input: Output)
/// Sends a completion signal to the subscriber.
///
/// - Parameter completion: A `Completion` instance which indicates whether publishing has finished normally or failed with an error.
final public func send(completion: Subscribers.Completion<Failure>)
}
/// A protocol for uniquely identifying publisher streams.
///
/// If you create a custom ``Subscription`` or ``Subscriber`` type, implement this protocol so that development tools can uniquely identify publisher chains in your app.
/// If your type is a class, Combine provides an implementation of ``CustomCombineIdentifierConvertible/combineIdentifier-1frze`` for you.
/// If your type is a structure, set up the identifier as follows:
///
/// let combineIdentifier = CombineIdentifier()
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol CustomCombineIdentifierConvertible {
/// A unique identifier for identifying publisher streams.
var combineIdentifier: CombineIdentifier { get }
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension CustomCombineIdentifierConvertible where Self : AnyObject {
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier { get }
}
/// A publisher that awaits subscription before running the supplied closure to create a publisher for the new subscriber.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct Deferred<DeferredPublisher> : Publisher where DeferredPublisher : Publisher {
/// The kind of values published by this publisher.
public typealias Output = DeferredPublisher.Output
/// The kind of errors this publisher might publish.
public typealias Failure = DeferredPublisher.Failure
/// The closure to execute when this deferred publisher receives a subscription.
///
/// The publisher returned by this closure immediately receives the incoming subscription.
public let createPublisher: () -> DeferredPublisher
/// Creates a deferred publisher.
///
/// - Parameter createPublisher: The closure to execute when calling `subscribe(_:)`.
public init(createPublisher: @escaping () -> DeferredPublisher)
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
public func receive<S>(subscriber: S) where S : Subscriber, DeferredPublisher.Failure == S.Failure, DeferredPublisher.Output == S.Input
}
/// A publisher that never publishes any values, and optionally finishes immediately.
///
/// You can create a ”Never” publisher — one which never sends values and never finishes or fails — with the initializer `Empty(completeImmediately: false)`.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct Empty<Output, Failure> : Publisher, Equatable where Failure : Error {
/// Creates an empty publisher.
///
/// - Parameter completeImmediately: A Boolean value that indicates whether the publisher should immediately finish.
public init(completeImmediately: Bool = true)
/// Creates an empty publisher with the given completion behavior and output and failure types.
///
/// Use this initializer to connect the empty publisher to subscribers or other publishers that have specific output and failure types.
///
/// - Parameters:
/// - completeImmediately: A Boolean value that indicates whether the publisher should immediately finish.
/// - outputType: The output type exposed by this publisher.
/// - failureType: The failure type exposed by this publisher.
public init(completeImmediately: Bool = true, outputType: Output.Type, failureType: Failure.Type)
/// A Boolean value that indicates whether the publisher immediately sends a completion.
///
/// If `true`, the publisher finishes immediately after sending a subscription to the subscriber. If `false`, it never completes.
public let completeImmediately: Bool
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Empty<Output, Failure>, rhs: Empty<Output, Failure>) -> Bool
}
/// A publisher that immediately terminates with the specified error.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct Fail<Output, Failure> : Publisher where Failure : Error {
/// Creates a publisher that immediately terminates with the specified failure.
///
/// - Parameter error: The failure to send when terminating the publisher.
public init(error: Failure)
/// Creates publisher with the given output type, that immediately terminates with the specified failure.
///
/// Use this initializer to create a `Fail` publisher that can work with subscribers or publishers that expect a given output type.
///
/// - Parameters:
/// - outputType: The output type exposed by this publisher.
/// - failure: The failure to send when terminating the publisher.
public init(outputType: Output.Type, failure: Failure)
/// The failure to send when terminating the publisher.
public let error: Failure
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Fail : Equatable where Failure : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Fail<Output, Failure>, rhs: Fail<Output, Failure>) -> Bool
}
/// A publisher that eventually produces a single value and then finishes or fails.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final public class Future<Output, Failure> : Publisher where Failure : Error {
/// A type that represents a closure to invoke in the future, when an element or error is available.
///
/// The promise closure receives one parameter: a `Result` that contains either a single element published by a ``Future``, or an error.
public typealias Promise = (Result<Output, Failure>) -> Void
/// Creates a publisher that invokes a promise closure when the publisher emits an element.
///
/// - Parameter attemptToFulfill: A ``Future/Promise`` that the publisher invokes when the publisher emits an element or terminates with an error.
public init(_ attemptToFulfill: @escaping (@escaping Future<Output, Failure>.Promise) -> Void)
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
final public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
}
/// A scheduler for performing synchronous actions.
///
/// You can only use this scheduler for immediate actions. If you attempt to schedule actions after a specific date, this scheduler ignores the date and performs them immediately.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct ImmediateScheduler : Scheduler {
/// The time type used by the immediate scheduler.
public struct SchedulerTimeType : Strideable {
/// Returns the distance to another immediate scheduler time; this distance is always `0` in the context of an immediate scheduler.
///
/// - Parameter other: The other scheduler time.
/// - Returns: `0`, as a `Stride`.
public func distance(to other: ImmediateScheduler.SchedulerTimeType) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Advances the time by the specified amount; this is meaningless in the context of an immediate scheduler.
///
/// - Parameter n: The amount to advance by. The `ImmediateScheduler` ignores this value.
/// - Returns: An empty `SchedulerTimeType`.
public func advanced(by n: ImmediateScheduler.SchedulerTimeType.Stride) -> ImmediateScheduler.SchedulerTimeType
/// The increment by which the immediate scheduler counts time.
public struct Stride : ExpressibleByFloatLiteral, Comparable, SignedNumeric, Codable, SchedulerTimeIntervalConvertible {
/// The type used when evaluating floating-point literals.
public typealias FloatLiteralType = Double
/// The type used when evaluating integer literals.
public typealias IntegerLiteralType = Int
/// The type used for expressing the stride’s magnitude.
public typealias Magnitude = Int
/// The value of this time interval in seconds.
public var magnitude: Int
/// Creates an immediate scheduler time interval from the given time interval.
public init(_ value: Int)
/// Creates an immediate scheduler time interval from an integer seconds value.
public init(integerLiteral value: Int)
/// Creates an immediate scheduler time interval from a floating-point seconds value.
public init(floatLiteral value: Double)
/// Creates an immediate scheduler time interval from a binary integer type.
///
/// If `exactly` can’t convert to an `Int`, the resulting time interval is `nil`.
public init?<T>(exactly source: T) where T : BinaryInteger
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride) -> Bool
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
public static func * (lhs: ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func + (lhs: ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func - (lhs: ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
public static func -= (lhs: inout ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride)
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
public static func *= (lhs: inout ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride)
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
public static func += (lhs: inout ImmediateScheduler.SchedulerTimeType.Stride, rhs: ImmediateScheduler.SchedulerTimeType.Stride)
/// Converts the specified number of seconds into an instance of this scheduler time type.
public static func seconds(_ s: Int) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Converts the specified number of seconds, as a floating-point value, into an instance of this scheduler time type.
public static func seconds(_ s: Double) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Converts the specified number of milliseconds into an instance of this scheduler time type.
public static func milliseconds(_ ms: Int) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Converts the specified number of microseconds into an instance of this scheduler time type.
public static func microseconds(_ us: Int) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Converts the specified number of nanoseconds into an instance of this scheduler time type.
public static func nanoseconds(_ ns: Int) -> ImmediateScheduler.SchedulerTimeType.Stride
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (a: ImmediateScheduler.SchedulerTimeType.Stride, b: ImmediateScheduler.SchedulerTimeType.Stride) -> Bool
}
}
/// A type that defines options accepted by the immediate scheduler.
public typealias SchedulerOptions = Never
/// The shared instance of the immediate scheduler.
///
/// You cannot create instances of the immediate scheduler yourself. Use only the shared instance.
public static let shared: ImmediateScheduler
/// Performs the action at the next possible opportunity.
public func schedule(options: ImmediateScheduler.SchedulerOptions?, _ action: @escaping () -> Void)
/// The immediate scheduler’s definition of the current moment in time.
public var now: ImmediateScheduler.SchedulerTimeType { get }
/// The minimum tolerance allowed by the immediate scheduler.
public var minimumTolerance: ImmediateScheduler.SchedulerTimeType.Stride { get }
/// Performs the action at some time after the specified date.
///
/// The immediate scheduler ignores `date` and performs the action immediately.
public func schedule(after date: ImmediateScheduler.SchedulerTimeType, tolerance: ImmediateScheduler.SchedulerTimeType.Stride, options: ImmediateScheduler.SchedulerOptions?, _ action: @escaping () -> Void)
/// Performs the action at some time after the specified date, at the specified frequency, optionally taking into account tolerance if possible.
///
/// The immediate scheduler ignores `date` and performs the action immediately.
public func schedule(after date: ImmediateScheduler.SchedulerTimeType, interval: ImmediateScheduler.SchedulerTimeType.Stride, tolerance: ImmediateScheduler.SchedulerTimeType.Stride, options: ImmediateScheduler.SchedulerOptions?, _ action: @escaping () -> Void) -> Cancellable
}
/// A publisher that emits an output to each subscriber just once, and then finishes.
///
/// You can use a ``Just`` publisher to start a chain of publishers. A ``Just`` publisher is also useful when replacing a value with ``Publishers/Catch``.
///
/// In contrast with <doc://com.apple.documentation/documentation/Swift/Result/Publisher>, a ``Just`` publisher can’t fail with an error. And unlike <doc://com.apple.documentation/documentation/Swift/Optional/Publisher>, a ``Just`` publisher always produces a value.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct Just<Output> : Publisher {
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Never
/// The one element that the publisher emits.
public let output: Output
/// Initializes a publisher that emits the specified output just once.
///
/// - Parameter output: The one element that the publisher emits.
public init(_ output: Output)
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
public func receive<S>(subscriber: S) where Output == S.Input, S : Subscriber, S.Failure == Just<Output>.Failure
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Just : Equatable where Output : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Just<Output>, rhs: Just<Output>) -> Bool
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Just where Output : Comparable {
public func min() -> Just<Output>
public func max() -> Just<Output>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Just where Output : Equatable {
public func contains(_ output: Output) -> Just<Bool>
public func removeDuplicates() -> Just<Output>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Just {
public func allSatisfy(_ predicate: (Output) -> Bool) -> Just<Bool>
public func tryAllSatisfy(_ predicate: (Output) throws -> Bool) -> Result<Bool, Error>.Publisher
public func collect() -> Just<[Output]>
public func compactMap<T>(_ transform: (Output) -> T?) -> Optional<T>.Publisher
public func min(by areInIncreasingOrder: (Output, Output) -> Bool) -> Just<Output>
public func max(by areInIncreasingOrder: (Output, Output) -> Bool) -> Just<Output>
public func prepend(_ elements: Output...) -> Publishers.Sequence<[Output], Just<Output>.Failure>
public func prepend<S>(_ elements: S) -> Publishers.Sequence<[Output], Just<Output>.Failure> where Output == S.Element, S : Sequence
public func append(_ elements: Output...) -> Publishers.Sequence<[Output], Just<Output>.Failure>
public func append<S>(_ elements: S) -> Publishers.Sequence<[Output], Just<Output>.Failure> where Output == S.Element, S : Sequence
public func contains(where predicate: (Output) -> Bool) -> Just<Bool>
public func tryContains(where predicate: (Output) throws -> Bool) -> Result<Bool, Error>.Publisher
public func count() -> Just<Int>
public func dropFirst(_ count: Int = 1) -> Optional<Output>.Publisher
public func drop(while predicate: (Output) -> Bool) -> Optional<Output>.Publisher
public func first() -> Just<Output>
public func first(where predicate: (Output) -> Bool) -> Optional<Output>.Publisher
public func last() -> Just<Output>
public func last(where predicate: (Output) -> Bool) -> Optional<Output>.Publisher
public func filter(_ isIncluded: (Output) -> Bool) -> Optional<Output>.Publisher
public func ignoreOutput() -> Empty<Output, Just<Output>.Failure>
public func map<T>(_ transform: (Output) -> T) -> Just<T>
public func tryMap<T>(_ transform: (Output) throws -> T) -> Result<T, Error>.Publisher
public func mapError<E>(_ transform: (Just<Output>.Failure) -> E) -> Result<Output, E>.Publisher where E : Error
public func output(at index: Int) -> Optional<Output>.Publisher
public func output<R>(in range: R) -> Optional<Output>.Publisher where R : RangeExpression, R.Bound == Int
public func prefix(_ maxLength: Int) -> Optional<Output>.Publisher
public func prefix(while predicate: (Output) -> Bool) -> Optional<Output>.Publisher
public func reduce<T>(_ initialResult: T, _ nextPartialResult: (T, Output) -> T) -> Result<T, Just<Output>.Failure>.Publisher
public func tryReduce<T>(_ initialResult: T, _ nextPartialResult: (T, Output) throws -> T) -> Result<T, Error>.Publisher
public func removeDuplicates(by predicate: (Output, Output) -> Bool) -> Just<Output>
public func tryRemoveDuplicates(by predicate: (Output, Output) throws -> Bool) -> Result<Output, Error>.Publisher
public func replaceError(with output: Output) -> Just<Output>
public func replaceEmpty(with output: Output) -> Just<Output>
public func retry(_ times: Int) -> Just<Output>
public func scan<T>(_ initialResult: T, _ nextPartialResult: (T, Output) -> T) -> Result<T, Just<Output>.Failure>.Publisher
public func tryScan<T>(_ initialResult: T, _ nextPartialResult: (T, Output) throws -> T) -> Result<T, Error>.Publisher
public func setFailureType<E>(to failureType: E.Type) -> Result<Output, E>.Publisher where E : Error
}
/// A type of object with a publisher that emits before the object has changed.
///
/// By default an ``ObservableObject`` synthesizes an ``ObservableObject/objectWillChange-2oa5v`` publisher that emits the changed value before any of its `@Published` properties changes.
///
/// class Contact: ObservableObject {
/// @Published var name: String
/// @Published var age: Int
///
/// init(name: String, age: Int) {
/// self.name = name
/// self.age = age
/// }
///
/// func haveBirthday() -> Int {
/// age += 1
/// return age
/// }
/// }
///
/// let john = Contact(name: "John Appleseed", age: 24)
/// cancellable = john.objectWillChange
/// .sink { _ in
/// print("\(john.age) will change")
/// }
/// print(john.haveBirthday())
/// // Prints "24 will change"
/// // Prints "25"
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol ObservableObject : AnyObject {
/// The type of publisher that emits before the object has changed.
associatedtype ObjectWillChangePublisher : Publisher = ObservableObjectPublisher where Self.ObjectWillChangePublisher.Failure == Never
/// A publisher that emits before the object has changed.
var objectWillChange: Self.ObjectWillChangePublisher { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension ObservableObject where Self.ObjectWillChangePublisher == ObservableObjectPublisher {
/// A publisher that emits before the object has changed.
public var objectWillChange: ObservableObjectPublisher { get }
}
/// A publisher that publishes changes from observable objects.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
final public class ObservableObjectPublisher : Publisher {
/// The kind of values published by this publisher.
public typealias Output = Void
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Never
/// Creates an observable object publisher instance.
public init()
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
final public func receive<S>(subscriber: S) where S : Subscriber, S.Failure == ObservableObjectPublisher.Failure, S.Input == ObservableObjectPublisher.Output
final public func send()
}
/// A subject that broadcasts elements to downstream subscribers.
///
/// As a concrete implementation of ``Subject``, the ``PassthroughSubject`` provides a convenient way to adapt existing imperative code to the Combine model.
///
/// Unlike ``CurrentValueSubject``, a ``PassthroughSubject`` doesn’t have an initial value or a buffer of the most recently-published element.
/// A ``PassthroughSubject`` drops values if there are no subscribers, or its current demand is zero.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final public class PassthroughSubject<Output, Failure> : Subject where Failure : Error {
public init()
/// Sends a subscription to the subscriber.
///
/// This call provides the ``Subject`` an opportunity to establish demand for any new upstream subscriptions.
///
/// - Parameter subscription: The subscription instance through which the subscriber can request elements.
final public func send(subscription: Subscription)
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
final public func receive<S>(subscriber: S) where Output == S.Input, Failure == S.Failure, S : Subscriber
/// Sends a value to the subscriber.
///
/// - Parameter value: The value to send.
final public func send(_ input: Output)
/// Sends a completion signal to the subscriber.
///
/// - Parameter completion: A `Completion` instance which indicates whether publishing has finished normally or failed with an error.
final public func send(completion: Subscribers.Completion<Failure>)
}
/// A type that publishes a property marked with an attribute.
///
/// Publishing a property with the `@Published` attribute creates a publisher of this type. You access the publisher with the `$` operator, as shown here:
///
/// class Weather {
/// @Published var temperature: Double
/// init(temperature: Double) {
/// self.temperature = temperature
/// }
/// }
///
/// let weather = Weather(temperature: 20)
/// cancellable = weather.$temperature
/// .sink() {
/// print ("Temperature now: \($0)")
/// }
/// weather.temperature = 25
///
/// // Prints:
/// // Temperature now: 20.0
/// // Temperature now: 25.0
///
/// When the property changes, publishing occurs in the property's `willSet` block, meaning subscribers receive the new value before it's actually set on the property. In the above example, the second time the sink executes its closure, it receives the parameter value `25`. However, if the closure evaluated `weather.temperature`, the value returned would be `20`.
///
/// > Important: The `@Published` attribute is class constrained. Use it with properties of classes, not with non-class types like structures.
///
/// ### See Also
///
/// - ``Combine/Publisher/assign(to:)``
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct Published<Value> {
/// Creates the published instance with an initial wrapped value.
///
/// Don't use this initializer directly. Instead, create a property with the `@Published` attribute, as shown here:
///
/// @Published var lastUpdated: Date = Date()
///
/// - Parameter wrappedValue: The publisher's initial value.
public init(wrappedValue: Value)
/// Creates the published instance with an initial value.
///
/// Don't use this initializer directly. Instead, create a property with the `@Published` attribute, as shown here:
///
/// @Published var lastUpdated: Date = Date()
///
/// - Parameter initialValue: The publisher's initial value.
public init(initialValue: Value)
/// A publisher for properties marked with the `@Published` attribute.
public struct Publisher : Publisher {
/// The kind of values published by this publisher.
public typealias Output = Value
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Never
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
public func receive<S>(subscriber: S) where Value == S.Input, S : Subscriber, S.Failure == Published<Value>.Publisher.Failure
}
/// The property for which this instance exposes a publisher.
///
/// The ``Published/projectedValue`` is the property accessed with the `$` operator.
public var projectedValue: Published<Value>.Publisher { mutating get set }
}
/// Declares that a type can transmit a sequence of values over time.
///
/// A publisher delivers elements to one or more ``Subscriber`` instances.
/// The subscriber’s ``Subscriber/Input`` and ``Subscriber/Failure`` associated types must match the ``Publisher/Output`` and ``Publisher/Failure`` types declared by the publisher.
/// The publisher implements the ``Publisher/receive(subscriber:)``method to accept a subscriber.
///
/// After this, the publisher can call the following methods on the subscriber:
/// - ``Subscriber/receive(subscription:)``: Acknowledges the subscribe request and returns a ``Subscription`` instance. The subscriber uses the subscription to demand elements from the publisher and can use it to cancel publishing.
/// - ``Subscriber/receive(_:)``: Delivers one element from the publisher to the subscriber.
/// - ``Subscriber/receive(completion:)``: Informs the subscriber that publishing has ended, either normally or with an error.
///
/// Every ``Publisher`` must adhere to this contract for downstream subscribers to function correctly.
///
/// Extensions on ``Publisher`` define a wide variety of _operators_ that you compose to create sophisticated event-processing chains.
/// Each operator returns a type that implements the ``Publisher`` protocol
/// Most of these types exist as extensions on the ``Publishers`` enumeration.
/// For example, the ``Publisher/map(_:)-99evh`` operator returns an instance of ``Publishers/Map``.
///
/// # Creating Your Own Publishers
///
/// Rather than implementing the ``Publisher`` protocol yourself, you can create your own publisher by using one of several types provided by the Combine framework:
///
/// - Use a concrete subclass of ``Subject``, such as ``PassthroughSubject``, to publish values on-demand by calling its ``Subject/send(_:)`` method.
/// - Use a ``CurrentValueSubject`` to publish whenever you update the subject’s underlying value.
/// - Add the `@Published` annotation to a property of one of your own types. In doing so, the property gains a publisher that emits an event whenever the property’s value changes. See the ``Published`` type for an example of this approach.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol Publisher {
/// The kind of values published by this publisher.
associatedtype Output
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
associatedtype Failure : Error
/// Attaches the specified subscriber to this publisher.
///
/// Implementations of ``Publisher`` must implement this method.
///
/// The provided implementation of ``Publisher/subscribe(_:)-4u8kn``calls this method.
///
/// - Parameter subscriber: The subscriber to attach to this ``Publisher``, after which it can receive values.
func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Applies a closure to create a subject that delivers elements to subscribers.
///
/// Use a multicast publisher when you have multiple downstream subscribers, but you want upstream publishers to only process one ``Subscriber/receive(_:)`` call per event. This is useful when upstream publishers are doing expensive work you don’t want to duplicate, like performing network requests.
///
/// In contrast with ``Publisher/multicast(subject:)``, this method produces a publisher that creates a separate ``Subject`` for each subscriber.
///
/// The following example uses a sequence publisher as a counter to publish three random numbers, generated by a ``Publisher/map(_:)-99evh`` operator.
/// It uses a ``Publisher/multicast(_:)`` operator whose closure creates a ``PassthroughSubject`` to share the same random number to each of two subscribers. Because the multicast publisher is a ``ConnectablePublisher``, publishing only begins after a call to ``ConnectablePublisher/connect()``.
///
/// let pub = ["First", "Second", "Third"].publisher
/// .map( { return ($0, Int.random(in: 0...100)) } )
/// .print("Random")
/// .multicast { PassthroughSubject<(String, Int), Never>() }
///
/// cancellable1 = pub
/// .sink { print ("Stream 1 received: \($0)")}
/// cancellable2 = pub
/// .sink { print ("Stream 2 received: \($0)")}
/// pub.connect()
///
/// // Prints:
/// // Random: receive value: (("First", 9))
/// // Stream 2 received: ("First", 9)
/// // Stream 1 received: ("First", 9)
/// // Random: receive value: (("Second", 46))
/// // Stream 2 received: ("Second", 46)
/// // Stream 1 received: ("Second", 46)
/// // Random: receive value: (("Third", 26))
/// // Stream 2 received: ("Third", 26)
/// // Stream 1 received: ("Third", 26)
///
/// In this example, the output shows that the ``Publisher/print(_:to:)`` operator receives each random value only one time, and then sends the value to both subscribers.
///
/// - Parameter createSubject: A closure to create a new ``Subject`` each time a subscriber attaches to the multicast publisher.
public func multicast<S>(_ createSubject: @escaping () -> S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output
/// Provides a subject to deliver elements to multiple subscribers.
///
/// Use a multicast publisher when you have multiple downstream subscribers, but you want upstream publishers to only process one ``Subscriber/receive(_:)`` call per event. This is useful when upstream publishers are doing expensive work you don’t want to duplicate, like performing network requests.
///
/// In contrast with ``Publisher/multicast(_:)``, this method produces a publisher that shares the provided ``Subject`` among all the downstream subscribers.
///
/// The following example uses a sequence publisher as a counter to publish three random numbers, generated by a ``Publisher/map(_:)-99evh`` operator.
/// It uses a ``Publisher/multicast(subject:)`` operator with a ``PassthroughSubject`` to share the same random number to each of two subscribers. Because the multicast publisher is a ``ConnectablePublisher``, publishing only begins after a call to ``ConnectablePublisher/connect()``.
///
/// let pub = ["First", "Second", "Third"].publisher
/// .map( { return ($0, Int.random(in: 0...100)) } )
/// .print("Random")
/// .multicast(subject: PassthroughSubject<(String, Int), Never>())
///
/// cancellable1 = pub
/// .sink { print ("Stream 1 received: \($0)")}
/// cancellable2 = pub
/// .sink { print ("Stream 2 received: \($0)")}
/// pub.connect()
///
/// // Prints:
/// // Random: receive value: (("First", 78))
/// // Stream 2 received: ("First", 78)
/// // Stream 1 received: ("First", 78)
/// // Random: receive value: (("Second", 98))
/// // Stream 2 received: ("Second", 98)
/// // Stream 1 received: ("Second", 98)
/// // Random: receive value: (("Third", 61))
/// // Stream 2 received: ("Third", 61)
/// // Stream 1 received: ("Third", 61)
///
/// In this example, the output shows that the ``Publisher/print(_:to:)`` operator receives each random value only one time, and then sends the value to both subscribers.
///
/// - Parameter subject: A subject to deliver elements to downstream subscribers.
public func multicast<S>(subject: S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// In contrast with ``Publisher/receive(on:options:)``, which affects downstream messages, ``Publisher/subscribe(on:options:)`` changes the execution context of upstream messages.
///
/// In the following example, the ``Publisher/subscribe(on:options:)`` operator causes `ioPerformingPublisher` to receive requests on `backgroundQueue`, while the ``Publisher/receive(on:options:)`` causes `uiUpdatingSubscriber` to receive elements and completion on `RunLoop.main`.
///
/// let ioPerformingPublisher == // Some publisher.
/// let uiUpdatingSubscriber == // Some subscriber that updates the UI.
///
/// ioPerformingPublisher
/// .subscribe(on: backgroundQueue)
/// .receive(on: RunLoop.main)
/// .subscribe(uiUpdatingSubscriber)
///
///
/// Using ``Publisher/subscribe(on:options:)`` also causes the upstream publisher to perform ``Cancellable/cancel()`` using the specfied scheduler.
///
/// - Parameters:
/// - scheduler: The scheduler used to send messages to upstream publishers.
/// - options: Options that customize the delivery of elements.
/// - Returns: A publisher which performs upstream operations on the specified scheduler.
public func subscribe<S>(on scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.SubscribeOn<Self, S> where S : Scheduler
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Measures and emits the time interval between events received from an upstream publisher.
///
/// Use ``Publisher/measureInterval(using:options:)`` to measure the time between events delivered from an upstream publisher.
///
/// In the example below, a 1-second <doc://com.apple.documentation/documentation/Foundation/Timer> is used as the data source for an event publisher; the ``Publisher/measureInterval(using:options:)`` operator reports the elapsed time between the reception of events on the main run loop:
///
/// cancellable = Timer.publish(every: 1, on: .main, in: .default)
/// .autoconnect()
/// .measureInterval(using: RunLoop.main)
/// .sink { print("\($0)", terminator: "\n") }
///
/// // Prints:
/// // Stride(magnitude: 1.0013610124588013)
/// // Stride(magnitude: 0.9992760419845581)
///
/// The output type of the returned publisher is the time interval of the provided scheduler.
///
/// This operator uses the provided scheduler’s ``Scheduler/now`` property to measure intervals between events.
///
/// - Parameters:
/// - scheduler: A scheduler to use for tracking the timing of events.
/// - options: Options that customize the delivery of elements.
/// - Returns: A publisher that emits elements representing the time interval between the elements it receives.
public func measureInterval<S>(using scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.MeasureInterval<Self, S> where S : Scheduler
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Omits elements from the upstream publisher until a given closure returns false, before republishing all remaining elements.
///
/// Use ``Publisher/drop(while:)`` to omit elements from an upstream publisher until the element received meets a condition you specify.
///
/// In the example below, the operator omits all elements in the stream until the first element arrives that’s a positive integer, after which the operator publishes all remaining elements:
///
/// let numbers = [-62, -1, 0, 10, 0, 22, 41, -1, 5]
/// cancellable = numbers.publisher
/// .drop { $0 <= 0 }
/// .sink { print("\($0)") }
///
/// // Prints: "10 0, 22 41 -1 5"
///
///
/// - Parameter predicate: A closure that takes an element as a parameter and returns a Boolean value indicating whether to drop the element from the publisher’s output.
/// - Returns: A publisher that skips over elements until the provided closure returns `false`.
public func drop(while predicate: @escaping (Self.Output) -> Bool) -> Publishers.DropWhile<Self>
/// Omits elements from the upstream publisher until an error-throwing closure returns false, before republishing all remaining elements.
///
/// Use ``Publisher/tryDrop(while:)`` to omit elements from an upstream until an error-throwing closure you provide returns false, after which the remaining items in the stream are published. If the closure throws, no elements are emitted and the publisher fails with an error.
///
/// In the example below, elements are ignored until `-1` is encountered in the stream and the closure returns `false`. The publisher then republishes the remaining elements and finishes normally. Conversely, if the `guard` value in the closure had been encountered, the closure would throw and the publisher would fail with an error.
///
/// struct RangeError: Error {}
/// var numbers = [1, 2, 3, 4, 5, 6, -1, 7, 8, 9, 10]
/// let range: CountableClosedRange<Int> = (1...100)
/// cancellable = numbers.publisher
/// .tryDrop {
/// guard $0 != 0 else { throw RangeError() }
/// return range.contains($0)
/// }
/// .sink(
/// receiveCompletion: { print ("completion: \($0)") },
/// receiveValue: { print ("value: \($0)") }
/// )
///
/// // Prints: "-1 7 8 9 10 completion: finished"
/// // If instead numbers was [1, 2, 3, 4, 5, 6, 0, -1, 7, 8, 9, 10], tryDrop(while:) would fail with a RangeError.
///
/// - Parameter predicate: A closure that takes an element as a parameter and returns a Boolean value indicating whether to drop the element from the publisher’s output.
/// - Returns: A publisher that skips over elements until the provided closure returns `false`, and then republishes all remaining elements. If the predicate closure throws, the publisher fails with an error.
public func tryDrop(while predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryDropWhile<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Republishes all elements that match a provided closure.
///
/// Combine’s ``Publisher/filter(_:)`` operator performs an operation similar to that of <doc://com.apple.documentation/documentation/Swift/Sequence/3018365-filter> in the Swift Standard Library: it uses a closure to test each element to determine whether to republish the element to the downstream subscriber.
///
/// The following example, uses a filter operation that receives an `Int` and only republishes a value if it’s even.
///
/// let numbers: [Int] = [1, 2, 3, 4, 5]
/// cancellable = numbers.publisher
/// .filter { $0 % 2 == 0 }
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: "2 4"
///
/// - Parameter isIncluded: A closure that takes one element and returns a Boolean value indicating whether to republish the element.
/// - Returns: A publisher that republishes all elements that satisfy the closure.
public func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self>
/// Republishes all elements that match a provided error-throwing closure.
///
/// Use ``Publisher/tryFilter(_:)`` to filter elements evaluated in an error-throwing closure. If the `isIncluded` closure throws an error, the publisher fails with that error.
///
/// In the example below, ``Publisher/tryFilter(_:)`` checks to see if the divisor provided by the publisher is zero, and throws a `DivisionByZeroError` and then terminates the publisher with the thrown error:
///
/// struct DivisionByZeroError: Error {}
///
/// let numbers: [Int] = [1, 2, 3, 4, 0, 5]
/// cancellable = numbers.publisher
/// .tryFilter{
/// if $0 == 0 {
/// throw DivisionByZeroError()
/// } else {
/// return $0 % 2 == 0
/// }
/// }
/// .sink(
/// receiveCompletion: { print ("\($0)") },
/// receiveValue: { print ("\($0)", terminator: " ") }
/// )
///
/// // Prints: "2 4 failure(DivisionByZeroError())".
///
/// - Parameter isIncluded: A closure that takes one element and returns a Boolean value that indicated whether to republish the element or throws an error.
/// - Returns: A publisher that republishes all elements that satisfy the closure.
public func tryFilter(_ isIncluded: @escaping (Self.Output) throws -> Bool) -> Publishers.TryFilter<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Raises a debugger signal when a provided closure needs to stop the process in the debugger.
///
/// Use ``Publisher/breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)`` to examine one or more stages of the subscribe/publish/completion process and stop in the debugger, based on conditions you specify. When any of the provided closures returns `true`, this operator raises the `SIGTRAP` signal to stop the process in the debugger. Otherwise, this publisher passes through values and completions as-is.
///
/// In the example below, a ``PassthroughSubject`` publishes strings to a breakpoint republisher. When the breakpoint receives the string “`DEBUGGER`”, it returns `true`, which stops the app in the debugger.
///
/// let publisher = PassthroughSubject<String?, Never>()
/// cancellable = publisher
/// .breakpoint(
/// receiveOutput: { value in return value == "DEBUGGER" }
/// )
/// .sink { print("\(String(describing: $0))" , terminator: " ") }
///
/// publisher.send("DEBUGGER")
///
/// // Prints: "error: Execution was interrupted, reason: signal SIGTRAP."
/// // Depending on your specific environment, the console messages may
/// // also include stack trace information, which is not shown here.
///
/// - Parameters:
/// - receiveSubscription: A closure that executes when the publisher receives a subscription. Return `true` from this closure to raise `SIGTRAP`, or false to continue.
/// - receiveOutput: A closure that executes when the publisher receives a value. Return `true` from this closure to raise `SIGTRAP`, or false to continue.
/// - receiveCompletion: A closure that executes when the publisher receives a completion. Return `true` from this closure to raise `SIGTRAP`, or false to continue.
/// - Returns: A publisher that raises a debugger signal when one of the provided closures returns `true`.
public func breakpoint(receiveSubscription: ((Subscription) -> Bool)? = nil, receiveOutput: ((Self.Output) -> Bool)? = nil, receiveCompletion: ((Subscribers.Completion<Self.Failure>) -> Bool)? = nil) -> Publishers.Breakpoint<Self>
/// Raises a debugger signal upon receiving a failure.
///
/// When the upstream publisher fails with an error, this publisher raises the `SIGTRAP` signal, which stops the process in the debugger. Otherwise, this publisher passes through values and completions as-is.
///
/// In this example a ``PassthroughSubject`` publishes strings, but its downstream ``Publisher/tryMap(_:)`` operator throws an error. This sends the error downstream as a ``Subscribers/Completion/failure(_:)``. The ``Publisher/breakpointOnError()`` operator receives this completion and stops the app in the debugger.
///
/// struct CustomError : Error {}
/// let publisher = PassthroughSubject<String?, Error>()
/// cancellable = publisher
/// .tryMap { stringValue in
/// throw CustomError()
/// }
/// .breakpointOnError()
/// .sink(
/// receiveCompletion: { completion in print("Completion: \(String(describing: completion))") },
/// receiveValue: { aValue in print("Result: \(String(describing: aValue))") }
/// )
///
/// publisher.send("TEST DATA")
///
/// // Prints: "error: Execution was interrupted, reason: signal SIGTRAP."
/// // Depending on your specific environment, the console messages may
/// // also include stack trace information, which is not shown here.
///
/// - Returns: A publisher that raises a debugger signal upon receiving a failure.
public func breakpointOnError() -> Publishers.Breakpoint<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Publishes a single Boolean value that indicates whether all received elements pass a given predicate.
///
/// Use the ``Publisher/allSatisfy(_:)`` operator to determine if all elements in a stream satisfy a criteria you provide. When this publisher receives an element, it runs the predicate against the element. If the predicate returns `false`, the publisher produces a `false` value and finishes. If the upstream publisher finishes normally, this publisher produces a `true` value and finishes.
///
/// In the example below, the ``Publisher/allSatisfy(_:)`` operator tests if each an integer array publisher’s elements fall into the `targetRange`:
///
/// let targetRange = (-1...100)
/// let numbers = [-1, 0, 10, 5]
/// numbers.publisher
/// .allSatisfy { targetRange.contains($0) }
/// .sink { print("\($0)") }
///
/// // Prints: "true"
///
/// With operators similar to ``Publisher/reduce(_:_:)``, this publisher produces at most one value.
///
/// > Note: Upon receiving any request greater than zero, this publisher requests unlimited elements from the upstream publisher.
///
/// - Parameter predicate: A closure that evaluates each received element. Return `true` to continue, or `false` to cancel the upstream and complete.
/// - Returns: A publisher that publishes a Boolean value that indicates whether all received elements pass a given predicate.
public func allSatisfy(_ predicate: @escaping (Self.Output) -> Bool) -> Publishers.AllSatisfy<Self>
/// Publishes a single Boolean value that indicates whether all received elements pass a given error-throwing predicate.
///
/// Use the ``Publisher/tryAllSatisfy(_:)`` operator to determine if all elements in a stream satisfy a criteria in an error-throwing predicate you provide. When this publisher receives an element, it runs the predicate against the element. If the predicate returns `false`, the publisher produces a `false` value and finishes. If the upstream publisher finishes normally, this publisher produces a `true` value and finishes. If the predicate throws an error, the publisher fails and passes the error to its downstream subscriber.
///
/// In the example below, an error-throwing predicate tests if each of an integer array publisher’s elements fall into the `targetRange`; the predicate throws an error if an element is zero and terminates the stream.
///
/// let targetRange = (-1...100)
/// let numbers = [-1, 10, 5, 0]
///
/// numbers.publisher
/// .tryAllSatisfy { anInt in
/// guard anInt != 0 else { throw RangeError() }
/// return targetRange.contains(anInt)
/// }
/// .sink(
/// receiveCompletion: { print ("completion: \($0)") },
/// receiveValue: { print ("value: \($0)") }
/// )
///
/// // Prints: "completion: failure(RangeError())"
///
/// With operators similar to ``Publisher/reduce(_:_:)``, this publisher produces at most one value.
///
/// > Note: Upon receiving any request greater than zero, this publisher requests unlimited elements from the upstream publisher.
///
/// - Parameter predicate: A closure that evaluates each received element. Return `true` to continue, or `false` to cancel the upstream and complete. The closure may throw an error, in which case the publisher cancels the upstream publisher and fails with the thrown error.
/// - Returns: A publisher that publishes a Boolean value that indicates whether all received elements pass a given predicate.
public func tryAllSatisfy(_ predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryAllSatisfy<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Attaches a subscriber with closure-based behavior.
///
/// Use ``Publisher/sink(receiveCompletion:receiveValue:)`` to observe values received by the publisher and process them using a closure you specify.
///
/// In this example, a <doc://com.apple.documentation/documentation/Swift/Range> publisher publishes integers to a ``Publisher/sink(receiveCompletion:receiveValue:)`` operator’s `receiveValue` closure that prints them to the console. Upon completion the ``Publisher/sink(receiveCompletion:receiveValue:)`` operator’s `receiveCompletion` closure indicates the successful termination of the stream.
///
/// let myRange = (0...3)
/// cancellable = myRange.publisher
/// .sink(receiveCompletion: { print ("completion: \($0)") },
/// receiveValue: { print ("value: \($0)") })
///
/// // Prints:
/// // value: 0
/// // value: 1
/// // value: 2
/// // value: 3
/// // completion: finished
///
/// This method creates the subscriber and immediately requests an unlimited number of values, prior to returning the subscriber.
/// The return value should be held, otherwise the stream will be canceled.
///
/// - parameter receiveComplete: The closure to execute on completion.
/// - parameter receiveValue: The closure to execute on receipt of a value.
/// - Returns: A cancellable instance, which you use when you end assignment of the received value. Deallocation of the result will tear down the subscription stream.
public func sink(receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void), receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Failure == Never {
/// Attaches a subscriber with closure-based behavior to a publisher that never fails.
///
/// Use ``Publisher/sink(receiveValue:)`` to observe values received by the publisher and print them to the console. This operator can only be used when the stream doesn’t fail, that is, when the publisher’s ``Publisher/Failure`` type is <doc://com.apple.documentation/documentation/Swift/Never>.
///
/// In this example, a <doc://com.apple.documentation/documentation/Swift/Range> publisher publishes integers to a ``Publisher/sink(receiveValue:)`` operator’s
/// `receiveValue` closure that prints them to the console:
///
/// let integers = (0...3)
/// integers.publisher
/// .sink { print("Received \($0)") }
///
/// // Prints:
/// // Received 0
/// // Received 1
/// // Received 2
/// // Received 3
///
/// This method creates the subscriber and immediately requests an unlimited number of values, prior to returning the subscriber.
/// The return value should be held, otherwise the stream will be canceled.
///
/// - parameter receiveValue: The closure to execute on receipt of a value.
/// - Returns: A cancellable instance, which you use when you end assignment of the received value. Deallocation of the result will tear down the subscription stream.
public func sink(receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Output : Equatable {
/// Publishes only elements that don’t match the previous element.
///
/// Use ``Publisher/removeDuplicates()`` to remove repeating elements from an upstream publisher. This operator has a two-element memory: the operator uses the current and previously published elements as the basis for its comparison.
///
/// In the example below, ``Publisher/removeDuplicates()`` triggers on the doubled, tripled, and quadrupled occurrences of `1`, `3`, and `4` respectively. Because the two-element memory considers only the current element and the previous element, the operator prints the final `0` in the example data since its immediate predecessor is `4`.
///
/// let numbers = [0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 0]
/// cancellable = numbers.publisher
/// .removeDuplicates()
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: "0 1 2 3 4 0"
///
/// - Returns: A publisher that consumes — rather than publishes — duplicate elements.
public func removeDuplicates() -> Publishers.RemoveDuplicates<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Publishes only elements that don’t match the previous element, as evaluated by a provided closure.
///
/// Use ``Publisher/removeDuplicates(by:)`` to remove repeating elements from an upstream publisher based upon the evaluation of the current and previously published elements using a closure you provide.
///
/// Use the ``Publisher/removeDuplicates(by:)`` operator when comparing types that don’t themselves implement `Equatable`, or if you need to compare values differently than the type’s `Equatable` implementation.
///
/// In the example below, the ``Publisher/removeDuplicates(by:)`` functionality triggers when the `x` property of the current and previous elements are equal, otherwise the operator publishes the current `Point` to the downstream subscriber:
///
/// struct Point {
/// let x: Int
/// let y: Int
/// }
///
/// let points = [Point(x: 0, y: 0), Point(x: 0, y: 1),
/// Point(x: 1, y: 1), Point(x: 2, y: 1)]
/// cancellable = points.publisher
/// .removeDuplicates { prev, current in
/// // Considers points to be duplicate if the x coordinate
/// // is equal, and ignores the y coordinate
/// prev.x == current.x
/// }
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: Point(x: 0, y: 0) Point(x: 1, y: 1) Point(x: 2, y: 1)
///
/// - Parameter predicate: A closure to evaluate whether two elements are equivalent, for purposes of filtering. Return `true` from this closure to indicate that the second element is a duplicate of the first.
/// - Returns: A publisher that consumes — rather than publishes — duplicate elements.
public func removeDuplicates(by predicate: @escaping (Self.Output, Self.Output) -> Bool) -> Publishers.RemoveDuplicates<Self>
/// Publishes only elements that don’t match the previous element, as evaluated by a provided error-throwing closure.
///
/// Use ``Publisher/tryRemoveDuplicates(by:)`` to remove repeating elements from an upstream publisher based upon the evaluation of elements using an error-throwing closure you provide. If your closure throws an error, the publisher terminates with the error.
///
/// In the example below, the closure provided to ``Publisher/tryRemoveDuplicates(by:)`` returns `true` when two consecutive elements are equal, thereby filtering out `0`,
/// `1`, `2`, and `3`. However, the closure throws an error when it encounters `4`. The publisher then terminates with this error.
///
/// struct BadValuesError: Error {}
/// let numbers = [0, 0, 0, 0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
/// cancellable = numbers.publisher
/// .tryRemoveDuplicates { first, second -> Bool in
/// if (first == 4 && second == 4) {
/// throw BadValuesError()
/// }
/// return first == second
/// }
/// .sink(
/// receiveCompletion: { print ("\($0)") },
/// receiveValue: { print ("\($0)", terminator: " ") }
/// )
///
/// // Prints: "0 1 2 3 4 failure(BadValuesError()"
///
/// - Parameter predicate: A closure to evaluate whether two elements are equivalent, for purposes of filtering. Return `true` from this closure to indicate that the second element is a duplicate of the first. If this closure throws an error, the publisher terminates with the thrown error.
/// - Returns: A publisher that consumes — rather than publishes — duplicate elements.
public func tryRemoveDuplicates(by predicate: @escaping (Self.Output, Self.Output) throws -> Bool) -> Publishers.TryRemoveDuplicates<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Decodes the output from the upstream using a specified decoder.
///
/// Use ``Publisher/decode(type:decoder:)`` with a <doc://com.apple.documentation/documentation/Foundation/JSONDecoder> (or a <doc://com.apple.documentation/documentation/Foundation/PropertyListDecoder> for property lists) to decode data received from a <doc://com.apple.documentation/documentation/Foundation/URLSession/DataTaskPublisher> or other data source using the <doc://com.apple.documentation/documentation/Swift/Decodable> protocol.
///
/// In this example, a ``PassthroughSubject`` publishes a JSON string. The JSON decoder parses the string, converting its fields according to the <doc://com.apple.documentation/documentation/Swift/Decodable> protocol implemented by `Article`, and successfully populating a new `Article`. The ``Publishers/Decode`` publisher then publishes the `Article` to the downstream. If a decoding operation fails, which happens in the case of missing or malformed data in the source JSON string, the stream terminates and passes the error to the downstream subscriber.
///
/// struct Article: Codable {
/// let title: String
/// let author: String
/// let pubDate: Date
/// }
///
/// let dataProvider = PassthroughSubject<Data, Never>()
/// cancellable = dataProvider
/// .decode(type: Article.self, decoder: JSONDecoder())
/// .sink(receiveCompletion: { print ("Completion: \($0)")},
/// receiveValue: { print ("value: \($0)") })
///
/// dataProvider.send(Data("{\"pubDate\":1574273638.575666, \"title\" : \"My First Article\", \"author\" : \"Gita Kumar\" }".utf8))
///
/// // Prints: ".sink() data received Article(title: "My First Article", author: "Gita Kumar", pubDate: 2050-11-20 18:13:58 +0000)"
///
/// - Parameters:
/// - type: The encoded data to decode into a struct that conforms to the <doc://com.apple.documentation/documentation/Swift/Decodable> protocol.
/// - decoder: A decoder that implements the ``TopLevelDecoder`` protocol.
/// - Returns: A publisher that decodes a given type using a specified decoder and publishes the result.
public func decode<Item, Coder>(type: Item.Type, decoder: Coder) -> Publishers.Decode<Self, Item, Coder> where Item : Decodable, Coder : TopLevelDecoder, Self.Output == Coder.Input
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Output : Encodable {
/// Encodes the output from upstream using a specified encoder.
///
/// Use ``Publisher/encode(encoder:)`` with a <doc://com.apple.documentation/documentation/Foundation/JSONDecoder> (or a <doc://com.apple.documentation/documentation/Foundation/PropertyListDecoder> for property lists) to encode an <doc://com.apple.documentation/documentation/Swift/Encodable> struct into <doc://com.apple.documentation/documentation/Foundation/Data> that could be used to make a JSON string (or written to disk as a binary plist in the case of property lists).
///
/// In this example, a ``PassthroughSubject`` publishes an `Article`. The ``Publisher/encode(encoder:)`` operator encodes the properties of the `Article` struct into a new JSON string according to the <doc://com.apple.documentation/documentation/Swift/Codable> protocol adopted by `Article`. The operator publishes the resulting JSON string to the downstream subscriber. If the encoding operation fails, which can happen in the case of complex properties that can’t be directly transformed into JSON, the stream terminates and the error is passed to the downstream subscriber.
///
/// struct Article: Codable {
/// let title: String
/// let author: String
/// let pubDate: Date
/// }
///
/// let dataProvider = PassthroughSubject<Article, Never>()
/// let cancellable = dataProvider
/// .encode(encoder: JSONEncoder())
/// .sink(receiveCompletion: { print ("Completion: \($0)") },
/// receiveValue: { data in
/// guard let stringRepresentation = String(data: data, encoding: .utf8) else { return }
/// print("Data received \(data) string representation: \(stringRepresentation)")
/// })
///
/// dataProvider.send(Article(title: "My First Article", author: "Gita Kumar", pubDate: Date()))
///
/// // Prints: "Data received 86 bytes string representation: {"title":"My First Article","author":"Gita Kumar","pubDate":606211803.279603}"
///
/// - Parameter encoder: An encoder that implements the ``TopLevelEncoder`` protocol.
/// - Returns: A publisher that encodes received elements using a specified encoder, and publishes the resulting data.
public func encode<Coder>(encoder: Coder) -> Publishers.Encode<Self, Coder> where Coder : TopLevelEncoder
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Output : Equatable {
/// Publishes a Boolean value upon receiving an element equal to the argument.
///
/// Use ``Publisher/contains(_:)`` to find the first element in an upstream that’s equal to the supplied argument. The contains publisher consumes all received elements until the upstream publisher produces a matching element. Upon finding the first match, it emits `true` and finishes normally. If the upstream finishes normally without producing a matching element, this publisher emits `false` and finishes.
///
/// In the example below, the ``Publisher/contains(_:)`` operator emits `true` the first time it receives the value `5` from the `numbers.publisher`, and then finishes normally.
///
/// let numbers = [-1, 5, 10, 5]
/// numbers.publisher
/// .contains(5)
/// .sink { print("\($0)") }
///
/// // Prints: "true"
///
/// - Parameter output: An element to match against.
/// - Returns: A publisher that emits the Boolean value `true` when the upstream publisher emits a matching value.
public func contains(_ output: Self.Output) -> Publishers.Contains<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Subscribes to an additional publisher and publishes a tuple upon receiving output from either publisher.
///
/// Use ``Publisher/combineLatest(_:)`` when you want the downstream subscriber to receive a tuple of the most-recent element from multiple publishers when any of them emit a value. To pair elements from multiple publishers, use ``Publisher/zip(_:)`` instead. To receive just the most-recent element from multiple publishers rather than tuples, use ``Publisher/merge(with:)-7qt71``.
///
/// The combined publisher passes through any requests to **all** upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t ``Subscribers/Demand/unlimited``, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
///
/// In this example, ``PassthroughSubject`` `pub1` and also `pub2` emit values; as ``Publisher/combineLatest(_:)`` receives input from either upstream publisher, it combines the latest value from each publisher into a tuple and publishes it.
///
/// let pub1 = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
///
/// cancellable = pub1
/// .combineLatest(pub2)
/// .sink { print("Result: \($0).") }
///
/// pub1.send(2)
/// pub2.send(2)
/// pub1.send(3)
/// pub1.send(45)
/// pub2.send(22)
///
/// // Prints:
/// // Result: (2, 2). // pub1 latest = 2, pub2 latest = 2
/// // Result: (3, 2). // pub1 latest = 3, pub2 latest = 2
/// // Result: (45, 2). // pub1 latest = 45, pub2 latest = 2
/// // Result: (45, 22). // pub1 latest = 45, pub2 latest = 22
///
/// When all upstream publishers finish, this publisher finishes. If an upstream publisher never publishes a value, this publisher never finishes.
///
/// - Parameter other: Another publisher to combine with this one.
/// - Returns: A publisher that receives and combines elements from this and another publisher.
public func combineLatest<P>(_ other: P) -> Publishers.CombineLatest<Self, P> where P : Publisher, Self.Failure == P.Failure
/// Subscribes to an additional publisher and invokes a closure upon receiving output from either publisher.
///
/// Use `combineLatest<P,T>(_:)` to combine the current and one additional publisher and transform them using a closure you specify to publish a new value to the downstream.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
///
/// In the example below, `combineLatest()` receives the most-recent values published by the two publishers, it multiplies them together, and republishes the result:
///
/// let pub1 = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
/// cancellable = pub1
/// .combineLatest(pub2) { (first, second) in
/// return first * second
/// }
/// .sink { print("Result: \($0).") }
///
/// pub1.send(2)
/// pub2.send(2)
/// pub1.send(9)
/// pub1.send(3)
/// pub2.send(12)
/// pub1.send(13)
/// //
/// // Prints:
/// //Result: 4. (pub1 latest = 2, pub2 latest = 2)
/// //Result: 18. (pub1 latest = 9, pub2 latest = 2)
/// //Result: 6. (pub1 latest = 3, pub2 latest = 2)
/// //Result: 36. (pub1 latest = 3, pub2 latest = 12)
/// //Result: 156. (pub1 latest = 13, pub2 latest = 12)
///
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
///
/// - Parameters:
/// - other: Another publisher to combine with this one.
/// - transform: A closure that receives the most-recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this and another publisher.
public func combineLatest<P, T>(_ other: P, _ transform: @escaping (Self.Output, P.Output) -> T) -> Publishers.Map<Publishers.CombineLatest<Self, P>, T> where P : Publisher, Self.Failure == P.Failure
/// Subscribes to two additional publishers and publishes a tuple upon receiving output from any of the publishers.
///
/// Use ``Publisher/combineLatest(_:_:)-5crqg`` when you want the downstream subscriber to receive a tuple of the most-recent element from multiple publishers when any of them emit a value. To combine elements from multiple publishers, use ``Publisher/zip(_:_:)-8d7k7`` instead. To receive just the most-recent element from multiple publishers rather than tuples, use ``Publisher/merge(with:_:)``.
///
/// The combined publisher passes through any requests to **all** upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t ``Subscribers/Demand/unlimited``, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
///
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
///
/// In this example, three instances of ``PassthroughSubject`` emit values; as ``Publisher/combineLatest(_:_:)-5crqg`` receives input from any of the upstream publishers, it combines the latest value from each publisher into a tuple and publishes it:
///
/// let pub = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
/// let pub3 = PassthroughSubject<Int, Never>()
///
/// cancellable = pub
/// .combineLatest(pub2, pub3)
/// .sink { print("Result: \($0).") }
///
/// pub.send(2)
/// pub2.send(2)
/// pub3.send(9)
///
/// pub.send(3)
/// pub2.send(12)
/// pub.send(13)
/// pub3.send(19)
///
/// // Prints:
/// // Result: (2, 2, 9).
/// // Result: (3, 2, 9).
/// // Result: (3, 12, 9).
/// // Result: (13, 12, 9).
/// // Result: (13, 12, 19).
///
/// If any of the combined publishers terminates with a failure, this publisher also fails.
/// - Parameters:
/// - publisher1: A second publisher to combine with the first publisher.
/// - publisher2: A third publisher to combine with the first publisher.
/// - Returns: A publisher that receives and combines elements from this publisher and two other publishers.
public func combineLatest<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.CombineLatest3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Subscribes to two additional publishers and invokes a closure upon receiving output from any of the publishers.
///
/// Use `combineLatest<P, Q>(_:,_:)` to combine the current and two additional publishers and transform them using a closure you specify to publish a new value to the downstream.
///
/// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
/// If any of the combined publishers terminates with a failure, this publisher also fails.
///
/// In the example below, `combineLatest()` receives the most-recent values published by three publishers, multiplies them together, and republishes the result:
///
/// let pub = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
/// let pub3 = PassthroughSubject<Int, Never>()
///
/// cancellable = pub
/// .combineLatest(pub2, pub3) { firstValue, secondValue, thirdValue in
/// return firstValue * secondValue * thirdValue
/// }
/// .sink { print("Result: \($0).") }
///
/// pub.send(2)
/// pub2.send(2)
/// pub3.send(10)
///
/// pub.send(9)
/// pub3.send(4)
/// pub2.send(12)
///
/// // Prints:
/// // Result: 40. // pub = 2, pub2 = 2, pub3 = 10
/// // Result: 180. // pub = 9, pub2 = 2, pub3 = 10
/// // Result: 72. // pub = 9, pub2 = 2, pub3 = 4
/// // Result: 432. // pub = 9, pub2 = 12, pub3 = 4
///
/// - Parameters:
/// - publisher1: A second publisher to combine with the first publisher.
/// - publisher2: A third publisher to combine with the first publisher.
/// - transform: A closure that receives the most-recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this publisher and two other publishers.
public func combineLatest<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.CombineLatest3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure
/// Subscribes to three additional publishers and publishes a tuple upon receiving output from any of the publishers.
///
/// Use ``Publisher/combineLatest(_:_:_:)-48buc`` when you want the downstream subscriber to receive a tuple of the most-recent element from multiple publishers when any of them emit a value. To combine elements from multiple publishers, use ``Publisher/zip(_:_:_:)-16rcy`` instead. To receive just the most-recent element from multiple publishers rather than tuples, use ``Publisher/merge(with:_:_:)``.
///
/// The combined publisher passes through any requests to **all** upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t ``Subscribers/Demand/unlimited``, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
///
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
///
/// In the example below, ``Publisher/combineLatest(_:_:_:)-48buc`` receives input from any of the publishers, combines the latest value from each publisher into a tuple and publishes it:
///
/// let pub = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
/// let pub3 = PassthroughSubject<Int, Never>()
/// let pub4 = PassthroughSubject<Int, Never>()
///
/// cancellable = pub
/// .combineLatest(pub2, pub3, pub4)
/// .sink { print("Result: \($0).") }
///
/// pub.send(2)
/// pub2.send(2)
/// pub3.send(9)
/// pub4.send(1)
///
/// pub.send(3)
/// pub2.send(12)
/// pub.send(13)
/// pub3.send(19)
/// //
/// // Prints:
/// // Result: (2, 2, 9, 1).
/// // Result: (3, 2, 9, 1).
/// // Result: (3, 12, 9, 1).
/// // Result: (13, 12, 9, 1).
/// // Result: (13, 12, 19, 1).
///
/// If any individual publisher of the combined set terminates with a failure, this publisher also fails.
///
/// - Parameters:
/// - publisher1: A second publisher to combine with the first publisher.
/// - publisher2: A third publisher to combine with the first publisher.
/// - publisher3: A fourth publisher to combine with the first publisher.
/// - Returns: A publisher that receives and combines elements from this publisher and three other publishers.
public func combineLatest<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.CombineLatest4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
/// Subscribes to three additional publishers and invokes a closure upon receiving output from any of the publishers.
///
/// Use ``Publisher/combineLatest(_:_:_:_:)`` when you need to combine the current and 3 additional publishers and transform the values using a closure in which you specify the published elements, to publish a new element.
///
/// The combined publisher passes through any requests to **all** upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t ``Subscribers/Demand/unlimited``, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most-recent value in each buffer.
///
/// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes.
///
/// In the example below, as ``Publisher/combineLatest(_:_:_:_:)`` receives the most-recent values published by four publishers, multiplies them together, and republishes the result:
///
/// let pub = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
/// let pub3 = PassthroughSubject<Int, Never>()
/// let pub4 = PassthroughSubject<Int, Never>()
///
/// cancellable = pub
/// .combineLatest(pub2, pub3, pub4) { firstValue, secondValue, thirdValue, fourthValue in
/// return firstValue * secondValue * thirdValue * fourthValue
/// }
/// .sink { print("Result: \($0).") }
///
/// pub.send(2)
/// pub2.send(2)
/// pub3.send(9)
/// pub4.send(1)
///
/// pub.send(3)
/// pub2.send(12)
/// pub.send(13)
/// pub3.send(19)
///
/// // Prints:
/// // Result: 36. // pub = 2, pub2 = 2, pub3 = 9, pub4 = 1
/// // Result: 54. // pub = 3, pub2 = 2, pub3 = 9, pub4 = 1
/// // Result: 324. // pub = 3, pub2 = 12, pub3 = 9, pub4 = 1
/// // Result: 1404. // pub = 13, pub2 = 12, pub3 = 9, pub4 = 1
/// // Result: 2964. // pub = 13, pub2 = 12, pub3 = 19, pub4 = 1
///
/// - Parameters:
/// - publisher1: A second publisher to combine with the first publisher.
/// - publisher2: A third publisher to combine with the first publisher.
/// - publisher3: A fourth publisher to combine with the first publisher.
/// - transform: A closure that receives the most-recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that receives and combines elements from this publisher and three other publishers.
public func combineLatest<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.CombineLatest4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Republishes elements up to the specified maximum count.
///
/// Use ``Publisher/prefix(_:)`` to limit the number of elements republished to the downstream subscriber.
///
/// In the example below, the ``Publisher/prefix(_:)`` operator limits its output to the first two elements before finishing normally:
///
/// let numbers = (0...10)
/// cancellable = numbers.publisher
/// .prefix(2)
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: "0 1"
///
/// - Parameter maxLength: The maximum number of elements to republish.
/// - Returns: A publisher that publishes up to the specified number of elements.
public func prefix(_ maxLength: Int) -> Publishers.Output<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Prints log messages for all publishing events.
///
/// Use ``Publisher/print(_:to:)`` to log messages the console.
///
/// In the example below, log messages are printed on the console:
///
/// let integers = (1...2)
/// cancellable = integers.publisher
/// .print("Logged a message", to: nil)
/// .sink { _ in }
///
/// // Prints:
/// // Logged a message: receive subscription: (1..<2)
/// // Logged a message: request unlimited
/// // Logged a message: receive value: (1)
/// // Logged a message: receive finished
///
/// - Parameters:
/// - prefix: A string —- which defaults to empty -— with which to prefix all log messages.
/// - stream: A stream for text output that receives messages, and which directs output to the console by default. A custom stream can be used to log messages to other destinations.
/// - Returns: A publisher that prints log messages for all publishing events.
public func print(_ prefix: String = "", to stream: TextOutputStream? = nil) -> Publishers.Print<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Republishes elements while a predicate closure indicates publishing should continue.
///
/// Use ``Publisher/prefix(while:)`` to emit values while elements from the upstream publisher meet a condition you specify. The publisher finishes when the closure returns `false`.
///
/// In the example below, the ``Publisher/prefix(while:)`` operator emits values while the element it receives is less than five:
///
/// let numbers = (0...10)
/// numbers.publisher
/// .prefix { $0 < 5 }
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: "0 1 2 3 4"
///
/// - Parameter predicate: A closure that takes an element as its parameter and returns a Boolean value that indicates whether publishing should continue.
/// - Returns: A publisher that passes through elements until the predicate indicates publishing should finish.
public func prefix(while predicate: @escaping (Self.Output) -> Bool) -> Publishers.PrefixWhile<Self>
/// Republishes elements while an error-throwing predicate closure indicates publishing should continue.
///
/// Use ``Publisher/tryPrefix(while:)`` to emit values from the upstream publisher that meet a condition you specify in an error-throwing closure.
/// The publisher finishes when the closure returns `false`. If the closure throws an error, the publisher fails with that error.
///
/// struct OutOfRangeError: Error {}
///
/// let numbers = (0...10).reversed()
/// cancellable = numbers.publisher
/// .tryPrefix {
/// guard $0 != 0 else {throw OutOfRangeError()}
/// return $0 <= numbers.max()!
/// }
/// .sink(
/// receiveCompletion: { print ("completion: \($0)", terminator: " ") },
/// receiveValue: { print ("\($0)", terminator: " ") }
/// )
///
/// // Prints: "10 9 8 7 6 5 4 3 2 1 completion: failure(OutOfRangeError()) "
///
/// - Parameter predicate: A closure that takes an element as its parameter and returns a Boolean value indicating whether publishing should continue.
/// - Returns: A publisher that passes through elements until the predicate throws or indicates publishing should finish.
public func tryPrefix(while predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryPrefixWhile<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Failure == Never {
/// Changes the failure type declared by the upstream publisher.
///
/// Use ``Publisher/setFailureType(to:)`` when you need set the error type of a publisher that cannot fail.
///
/// Conversely, if the upstream can fail, you would use ``Publisher/mapError(_:)`` to provide instructions on converting the error types to needed by the downstream publisher’s inputs.
///
/// The following example has two publishers with mismatched error types: `pub1`’s error type is <doc://com.apple.documentation/documentation/Swift/Never>, and `pub2`’s error type is <doc://com.apple.documentation/documentation/Swift/Error>. Because of the mismatch, the ``Publisher/combineLatest(_:)`` operator requires that `pub1` use ``Publisher/setFailureType(to:)`` to make it appear that `pub1` can produce the <doc://com.apple.documentation/documentation/Swift/Error> type, like `pub2` can.
///
/// let pub1 = [0, 1, 2, 3, 4, 5].publisher
/// let pub2 = CurrentValueSubject<Int, Error>(0)
/// let cancellable = pub1
/// .setFailureType(to: Error.self)
/// .combineLatest(pub2)
/// .sink(
/// receiveCompletion: { print ("completed: \($0)") },
/// receiveValue: { print ("value: \($0)")}
/// )
///
/// // Prints: "value: (5, 0)".
///
/// - Parameter failureType: The `Failure` type presented by this publisher.
/// - Returns: A publisher that appears to send the specified failure type.
public func setFailureType<E>(to failureType: E.Type) -> Publishers.SetFailureType<Self, E> where E : Error
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Publishes a Boolean value upon receiving an element that satisfies the predicate closure.
///
/// Use ``Publisher/contains(where:)`` to find the first element in an upstream that satisfies the closure you provide. This operator consumes elements produced from the upstream publisher until the upstream publisher produces a matching element.
///
/// This operator is useful when the upstream publisher produces elements that don’t conform to `Equatable`.
///
/// In the example below, the ``Publisher/contains(where:)`` operator tests elements against the supplied closure and emits `true` for the first elements that’s greater than `4`, and then finishes normally.
///
/// let numbers = [-1, 0, 10, 5]
/// numbers.publisher
/// .contains {$0 > 4}
/// .sink { print("\($0)") }
///
/// // Prints: "true"
///
/// - Parameter predicate: A closure that takes an element as its parameter and returns a Boolean value that indicates whether the element satisfies the closure’s comparison logic.
/// - Returns: A publisher that emits the Boolean value `true` when the upstream publisher emits a matching value.
public func contains(where predicate: @escaping (Self.Output) -> Bool) -> Publishers.ContainsWhere<Self>
/// Publishes a Boolean value upon receiving an element that satisfies the throwing predicate closure.
///
/// Use ``Publisher/tryContains(where:)`` to find the first element in an upstream that satisfies the error-throwing closure you provide.
///
/// This operator consumes elements produced from the upstream publisher until the upstream publisher either:
///
/// - Produces a matching element, after which it emits `true` and the publisher finishes normally.
/// - Emits `false` if no matching element is found and the publisher finishes normally.
///
/// If the predicate throws an error, the publisher fails, passing the error to its downstream.
///
/// In the example below, the ``Publisher/tryContains(where:)`` operator tests values to find an element less than `10`; when the closure finds an odd number, like `3`, the publisher terminates with an `IllegalValueError`.
///
/// struct IllegalValueError: Error {}
///
/// let numbers = [3, 2, 10, 5, 0, 9]
/// numbers.publisher
/// .tryContains {
/// if ($0 % 2 != 0) {
/// throw IllegalValueError()
/// }
/// return $0 < 10
/// }
/// .sink(
/// receiveCompletion: { print ("completion: \($0)") },
/// receiveValue: { print ("value: \($0)") }
/// )
///
/// // Prints: "completion: failure(IllegalValueError())"
///
/// - Parameter predicate: A closure that takes an element as its parameter and returns a Boolean value that indicates whether the element satisfies the closure’s comparison logic.
/// - Returns: A publisher that emits the Boolean value `true` when the upstream publisher emits a matching value.
public func tryContains(where predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryContainsWhere<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Attaches the specified subscriber to this publisher.
///
/// Always call this function instead of ``Publisher/receive(subscriber:)``.
/// Adopters of ``Publisher`` must implement ``Publisher/receive(subscriber:)``. The implementation of ``Publisher/subscribe(_:)-4u8kn`` provided by ``Publisher`` calls through to ``Publisher/receive(subscriber:)``.
///
/// - Parameter subscriber: The subscriber to attach to this publisher. After attaching, the subscriber can start to receive values.
public func subscribe<S>(_ subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}
extension Publisher where Self.Failure == Never {
/// Republishes elements received from a publisher, by assigning them to a property marked as a publisher.
///
/// Use this operator when you want to receive elements from a publisher and republish them through a property marked with the `@Published` attribute. The `assign(to:)` operator manages the life cycle of the subscription, canceling the subscription automatically when the ``Published`` instance deinitializes. Because of this, the `assign(to:)` operator doesn't return an ``AnyCancellable`` that you're responsible for like ``assign(to:on:)`` does.
///
/// The example below shows a model class that receives elements from an internal <doc://com.apple.documentation/documentation/Foundation/Timer/TimerPublisher>, and assigns them to a `@Published` property called `lastUpdated`:
///
/// class MyModel: ObservableObject {
/// @Published var lastUpdated: Date = Date()
/// init() {
/// Timer.publish(every: 1.0, on: .main, in: .common)
/// .autoconnect()
/// .assign(to: $lastUpdated)
/// }
/// }
///
/// If you instead implemented `MyModel` with `assign(to: lastUpdated, on: self)`, storing the returned ``AnyCancellable`` instance could cause a reference cycle, because the ``Subscribers/Assign`` subscriber would hold a strong reference to `self`. Using `assign(to:)` solves this problem.
///
/// - Parameter published: A property marked with the `@Published` attribute, which receives and republishes all elements received from the upstream publisher.
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public func assign(to published: inout Published<Self.Output>.Publisher)
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Failure == Never {
/// Creates a connectable wrapper around the publisher.
///
/// In the following example, ``Publisher/makeConnectable()`` wraps its upstream publisher (an instance of ``Publishers/Share``) with a ``ConnectablePublisher``. Without this, the first sink subscriber would receive all the elements from the sequence publisher and cause it to complete before the second subscriber attaches. By making the publisher connectable, the publisher doesn’t produce any elements until after the ``ConnectablePublisher/connect()`` call.
///
/// let subject = Just<String>("Sent")
/// let pub = subject
/// .share()
/// .makeConnectable()
/// cancellable1 = pub.sink { print ("Stream 1 received: \($0)") }
///
/// // For example purposes, use DispatchQueue to add a second subscriber
/// // a second later, and then connect to the publisher a second after that.
/// DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
/// self.cancellable2 = pub.sink { print ("Stream 2 received: \($0)") }
/// }
/// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
/// self.connectable = pub.connect()
/// }
/// // Prints:
/// // Stream 2 received: Sent
/// // Stream 1 received: Sent
///
/// > Note: The ``ConnectablePublisher/connect()`` operator returns a ``Cancellable`` instance that you must retain. You can also use this instance to cancel publishing.
///
/// - Returns: A ``ConnectablePublisher`` wrapping this publisher.
public func makeConnectable() -> Publishers.MakeConnectable<Self>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Collects all received elements, and emits a single array of the collection when the upstream publisher finishes.
///
/// Use ``Publisher/collect()`` to gather elements into an array that the operator emits after the upstream publisher finishes.
///
/// If the upstream publisher fails with an error, this publisher forwards the error to the downstream receiver instead of sending its output.
///
/// This publisher requests an unlimited number of elements from the upstream publisher and uses an unbounded amount of memory to store the received values. The publisher may exert memory pressure on the system for very large sets of elements.
///
/// The ``Publisher/collect()`` operator only sends the collected array to its downstream receiver after a request whose demand is greater than 0 items. Otherwise, ``Publisher/collect()`` waits until it receives a non-zero request.
///
/// In the example below, an Integer range is a publisher that emits an array of integers:
///
/// let numbers = (0...10)
/// cancellable = numbers.publisher
/// .collect()
/// .sink { print("\($0)") }
///
/// // Prints: "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// - Returns: A publisher that collects all received items and returns them as an array upon completion.
public func collect() -> Publishers.Collect<Self>
/// Collects up to the specified number of elements, and then emits a single array of the collection.
///
/// Use ``Publisher/collect(_:)`` to emit arrays of at most `count` elements from an upstream publisher. If the upstream publisher finishes before collecting the specified number of elements, the publisher sends an array of only the items it received. This may be fewer than `count` elements.
///
/// If the upstream publisher fails with an error, this publisher forwards the error to the downstream receiver instead of sending its output.
///
/// In the example below, the ``Publisher/collect(_:)`` operator emits one partial and two full arrays based on the requested collection size of `5`:
///
/// let numbers = (0...10)
/// cancellable = numbers.publisher
/// .collect(5)
/// .sink { print("\($0), terminator: " "") }
///
/// // Prints "[0, 1, 2, 3, 4] [5, 6, 7, 8, 9] [10] "
///
/// > Note: When this publisher receives a request for `.max(n)` elements, it requests `.max(count * n)` from the upstream publisher.
///
/// - Parameter count: The maximum number of received elements to buffer before publishing.
/// - Returns: A publisher that collects up to the specified number of elements, and then publishes them as an array.
public func collect(_ count: Int) -> Publishers.CollectByCount<Self>
/// Collects elements by a given time-grouping strategy, and emits a single array of the collection.
///
/// Use ``Publisher/collect(_:options:)`` to emit arrays of elements on a schedule specified by a ``Scheduler`` and `Stride` that you provide. At the end of each scheduled interval, the publisher sends an array that contains the items it collected. If the upstream publisher finishes before filling the buffer, the publisher sends an array that contains items it received. This may be fewer than the number of elements specified in the requested `Stride`.
///
/// If the upstream publisher fails with an error, this publisher forwards the error to the downstream receiver instead of sending its output.
///
/// The example above collects timestamps generated on a one-second <doc://com.apple.documentation/documentation/Foundation/Timer> in groups (`Stride`) of five.
///
/// let sub = Timer.publish(every: 1, on: .main, in: .default)
/// .autoconnect()
/// .collect(.byTime(RunLoop.main, .seconds(5)))
/// .sink { print("\($0)", terminator: "\n\n") }
///
/// // Prints: "[2020-01-24 00:54:46 +0000, 2020-01-24 00:54:47 +0000,
/// // 2020-01-24 00:54:48 +0000, 2020-01-24 00:54:49 +0000,
/// // 2020-01-24 00:54:50 +0000]"
///
/// > Note: When this publisher receives a request for `.max(n)` elements, it requests `.max(count * n)` from the upstream publisher.
///
/// - Parameters:
/// - strategy: The timing group strategy used by the operator to collect and publish elements.
/// - options: ``Scheduler`` options to use for the strategy.
/// - Returns: A publisher that collects elements by a given strategy, and emits a single array of the collection.
public func collect<S>(_ strategy: Publishers.TimeGroupingStrategy<S>, options: S.SchedulerOptions? = nil) -> Publishers.CollectByTime<Self, S> where S : Scheduler
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Specifies the scheduler on which to receive elements from the publisher.
///
/// You use the ``Publisher/receive(on:options:)`` operator to receive results and completion on a specific scheduler, such as performing UI work on the main run loop. In contrast with ``Publisher/subscribe(on:options:)``, which affects upstream messages, ``Publisher/receive(on:options:)`` changes the execution context of downstream messages.
///
/// In the following example, the ``Publisher/subscribe(on:options:)`` operator causes `jsonPublisher` to receive requests on `backgroundQueue`, while the
/// ``Publisher/receive(on:options:)`` causes `labelUpdater` to receive elements and completion on `RunLoop.main`.
///
/// let jsonPublisher = MyJSONLoaderPublisher() // Some publisher.
/// let labelUpdater = MyLabelUpdateSubscriber() // Some subscriber that updates the UI.
///
/// jsonPublisher
/// .subscribe(on: backgroundQueue)
/// .receive(on: RunLoop.main)
/// .subscribe(labelUpdater)
///
///
/// Prefer ``Publisher/receive(on:options:)`` over explicit use of dispatch queues when performing work in subscribers. For example, instead of the following pattern:
///
/// pub.sink {
/// DispatchQueue.main.async {
/// // Do something.
/// }
/// }
///
/// Use this pattern instead:
///
/// pub.receive(on: DispatchQueue.main).sink {
/// // Do something.
/// }
///
/// > Note: ``Publisher/receive(on:options:)`` doesn’t affect the scheduler used to call the subscriber’s ``Subscriber/receive(subscription:)`` method.
///
/// - Parameters:
/// - scheduler: The scheduler the publisher uses for element delivery.
/// - options: Scheduler options used to customize element delivery.
/// - Returns: A publisher that delivers elements using the specified scheduler.
public func receive<S>(on scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.ReceiveOn<Self, S> where S : Scheduler
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Publishes the value of a key path.
///
/// In the following example, the ``Publisher/map(_:)-6sm0a`` operator uses the Swift key path syntax to access the `die` member of the `DiceRoll` structure published by the ``Just`` publisher.
///
/// The downstream sink subscriber receives only the value of this `Int`, not the entire `DiceRoll`.
///
/// struct DiceRoll {
/// let die: Int
/// }
///
/// cancellable = Just(DiceRoll(die:Int.random(in:1...6)))
/// .map(\.die)
/// .sink {
/// print ("Rolled: \($0)")
/// }
/// // Prints "Rolled: 3" (or some other random value).
///
/// - Parameter keyPath: The key path of a property on `Output`.
/// - Returns: A publisher that publishes the value of the key path.
public func map<T>(_ keyPath: KeyPath<Self.Output, T>) -> Publishers.MapKeyPath<Self, T>
/// Publishes the values of two key paths as a tuple.
///
/// In the following example, the ``Publisher/map(_:_:)`` operator uses the Swift key path syntax to access the `die1` and `die2` members of the `DiceRoll` structure published by the ``Just`` publisher.
///
/// The downstream sink subscriber receives only these two values (as an `(Int, Int)` tuple), not the entire `DiceRoll`.
///
/// struct DiceRoll {
/// let die1: Int
/// let die2: Int
/// }
///
/// cancellable = Just(DiceRoll(die1:Int.random(in:1...6),
/// die2: Int.random(in:1...6)))
/// .map(\.die1, \.die2)
/// .sink { values in
/// print ("Rolled: \(values.0), \(values.1) (total: \(values.0 + values.1))")
/// }
/// // Prints "Rolled: 6, 4 (total: 10)" (or other random values).
///
/// - Parameters:
/// - keyPath0: The key path of a property on `Output`.
/// - keyPath1: The key path of another property on `Output`.
/// - Returns: A publisher that publishes the values of two key paths as a tuple.
public func map<T0, T1>(_ keyPath0: KeyPath<Self.Output, T0>, _ keyPath1: KeyPath<Self.Output, T1>) -> Publishers.MapKeyPath2<Self, T0, T1>
/// Publishes the values of three key paths as a tuple.
///
/// In the following example, the ``Publisher/map(_:_:_:)`` operator uses the Swift key path syntax to access the `die1`, `die2`, and `die3` members of the `DiceRoll` structure published by the ``Just`` publisher.
///
/// The downstream sink subscriber receives only these three values (as an `(Int, Int, Int)` tuple), not the entire `DiceRoll`.
///
/// struct DiceRoll {
/// let die1: Int
/// let die2: Int
/// let die3: Int
/// }
///
/// cancellable = Just(DiceRoll(die1:Int.random(in:1...6),
/// die2: Int.random(in:1...6),
/// die3: Int.random(in:1...6)))
/// .map(\.die1, \.die2, \.die3)
/// .sink { values in
/// print ("Rolled: \(values.0), \(values.1), \(values.2) (total \(values.0 + values.1 + values.2))")
/// }
/// // Prints "Rolled: 5, 4, 2 (total 11)" (or other random values).
///
/// - Parameters:
/// - keyPath0: The key path of a property on `Output`.
/// - keyPath1: The key path of a second property on `Output`.
/// - keyPath2: The key path of a third property on `Output`.
/// - Returns: A publisher that publishes the values of three key paths as a tuple.
public func map<T0, T1, T2>(_ keyPath0: KeyPath<Self.Output, T0>, _ keyPath1: KeyPath<Self.Output, T1>, _ keyPath2: KeyPath<Self.Output, T2>) -> Publishers.MapKeyPath3<Self, T0, T1, T2>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Republishes elements until another publisher emits an element.
///
/// After the second publisher publishes an element, the publisher returned by this method finishes.
///
/// - Parameter publisher: A second publisher.
/// - Returns: A publisher that republishes elements until the second publisher publishes an element.
public func prefix<P>(untilOutputFrom publisher: P) -> Publishers.PrefixUntilOutput<Self, P> where P : Publisher
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Attaches the specified subject to this publisher.
///
/// - Parameter subject: The subject to attach to this publisher.
public func subscribe<S>(_ subject: S) -> AnyCancellable where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Applies a closure that collects each element of a stream and publishes a final result upon completion.
///
/// Use ``Publisher/reduce(_:_:)`` to collect a stream of elements and produce an accumulated value based on a closure you provide.
///
/// In the following example, the ``Publisher/reduce(_:_:)`` operator collects all the integer values it receives from its upstream publisher:
///
/// let numbers = (0...10)
/// cancellable = numbers.publisher
/// .reduce(0, { accum, next in accum + next })
/// .sink { print("\($0)") }
///
/// // Prints: "55"
///
/// - Parameters:
/// - initialResult: The value that the closure receives the first time it’s called.
/// - nextPartialResult: A closure that produces a new value by taking the previously-accumulated value and the next element it receives from the upstream publisher.
/// - Returns: A publisher that applies the closure to all received elements and produces an accumulated value when the upstream publisher finishes. If ``Publisher/reduce(_:_:)`` receives an error from the upstream publisher, the operator delivers it to the downstream subscriber, the publisher terminates and publishes no value.
public func reduce<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) -> T) -> Publishers.Reduce<Self, T>
/// Applies an error-throwing closure that collects each element of a stream and publishes a final result upon completion.
///
/// Use ``Publisher/tryReduce(_:_:)`` to collect a stream of elements and produce an accumulated value based on an error-throwing closure you provide.
/// If the closure throws an error, the publisher fails and passes the error to its subscriber.
///
/// In the example below, the publisher’s `0` element causes the `myDivide(_:_:)` function to throw an error and publish the <doc://com.apple.documentation/documentation/Swift/Double/1641611-nan> result:
///
/// struct DivisionByZeroError: Error {}
/// func myDivide(_ dividend: Double, _ divisor: Double) throws -> Double {
/// guard divisor != 0 else { throw DivisionByZeroError() }
/// return dividend / divisor
/// }
///
/// var numbers: [Double] = [5, 4, 3, 2, 1, 0]
/// numbers.publisher
/// .tryReduce(numbers.first!, { accum, next in try myDivide(accum, next) })
/// .catch({ _ in Just(Double.nan) })
/// .sink { print("\($0)") }
///
/// - Parameters:
/// - initialResult: The value that the closure receives the first time it’s called.
/// - nextPartialResult: An error-throwing closure that takes the previously-accumulated value and the next element from the upstream publisher to produce a new value.
///
/// - Returns: A publisher that applies the closure to all received elements and produces an accumulated value when the upstream publisher finishes.
public func tryReduce<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) throws -> T) -> Publishers.TryReduce<Self, T>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Calls a closure with each received element and publishes any returned optional that has a value.
///
/// Combine’s ``Publisher/compactMap(_:)`` operator performs a function similar to that of <doc://com.apple.documentation/documentation/Swift/Sequence/2950916-compactmap> in the Swift standard library: the ``Publisher/compactMap(_:)`` operator in Combine removes `nil` elements in a publisher’s stream and republishes non-`nil` elements to the downstream subscriber.
///
/// The example below uses a range of numbers as the source for a collection based publisher. The ``Publisher/compactMap(_:)`` operator consumes each element from the `numbers` publisher attempting to access the dictionary using the element as the key. If the example’s dictionary returns a `nil`, due to a non-existent key, ``Publisher/compactMap(_:)`` filters out the `nil` (missing) elements.
///
/// let numbers = (0...5)
/// let romanNumeralDict: [Int : String] =
/// [1: "I", 2: "II", 3: "III", 5: "V"]
///
/// cancellable = numbers.publisher
/// .compactMap { romanNumeralDict[$0] }
/// .sink { print("\($0)", terminator: " ") }
///
/// // Prints: "I II III V"
///
/// - Parameter transform: A closure that receives a value and returns an optional value.
/// - Returns: Any non-`nil` optional results of the calling the supplied closure.
public func compactMap<T>(_ transform: @escaping (Self.Output) -> T?) -> Publishers.CompactMap<Self, T>
/// Calls an error-throwing closure with each received element and publishes any returned optional that has a value.
///
/// Use ``Publisher/tryCompactMap(_:)`` to remove `nil` elements from a publisher’s stream based on an error-throwing closure you provide. If the closure throws an error, the publisher cancels the upstream publisher and sends the thrown error to the downstream subscriber as a ``Publisher/Failure``.
///
/// The following example uses an array of numbers as the source for a collection-based publisher. A ``Publisher/tryCompactMap(_:)`` operator consumes each integer from the publisher and uses a dictionary to transform the numbers from its Arabic to Roman numerals, as an optional <doc://com.apple.documentation/documentation/Swift/String>.
///
/// If the closure called by ``Publisher/tryCompactMap(_:)`` fails to look up a Roman numeral, it returns the optional String `(unknown)`.
///
/// If the closure called by ``Publisher/tryCompactMap(_:)`` determines the input is `0`, it throws an error. The ``Publisher/tryCompactMap(_:)`` operator catches this error and stops publishing, sending a ``Subscribers/Completion/failure(_:)`` that wraps the error.
///
/// struct ParseError: Error {}
/// func romanNumeral(from: Int) throws -> String? {
/// let romanNumeralDict: [Int : String] =
/// [1: "I", 2: "II", 3: "III", 4: "IV", 5: "V"]
/// guard from != 0 else { throw ParseError() }
/// return romanNumeralDict[from]
/// }
/// let numbers = [6, 5, 4, 3, 2, 1, 0]
/// cancellable = numbers.publisher
/// .tryCompactMap { try romanNumeral(from: $0) }
/// .sink(
/// receiveCompletion: { print ("\($0)") },
/// receiveValue: { print ("\($0)", terminator: " ") }
/// )
///
/// // Prints: "(Unknown) V IV III II I failure(ParseError())"
///
/// - Parameter transform: An error-throwing closure that receives a value and returns an optional value.
/// - Returns: Any non-`nil` optional results of calling the supplied closure.
public func tryCompactMap<T>(_ transform: @escaping (Self.Output) throws -> T?) -> Publishers.TryCompactMap<Self, T>
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher {
/// Combines elements from this publisher with those from another publisher, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:)-7fk3a`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:)``. To combine elements from multiple upstream publishers, use ``Publisher/zip(_:)``.
///
/// In this example, as ``Publisher/merge(with:)-7fk3a`` receives input from either upstream publisher, it republishes it to the downstream:
///
/// let publisher = PassthroughSubject<Int, Never>()
/// let pub2 = PassthroughSubject<Int, Never>()
///
/// cancellable = publisher
/// .merge(with: pub2)
/// .sink { print("\($0)", terminator: " " )}
///
/// publisher.send(2)
/// pub2.send(2)
/// publisher.send(3)
/// pub2.send(22)
/// publisher.send(45)
/// pub2.send(22)
/// publisher.send(17)
///
/// // Prints: "2 2 3 22 45 22 17"
///
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameter other: Another publisher.
/// - Returns: A publisher that emits an event when either upstream publisher emits an event.
public func merge<P>(with other: P) -> Publishers.Merge<Self, P> where P : Publisher, Self.Failure == P.Failure, Self.Output == P.Output
/// Combines elements from this publisher with those from two other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:)-5crqg``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:)-8d7k7``.
///
/// In this example, as ``Publisher/merge(with:_:)`` receives input from the upstream publishers, it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
///
/// cancellable = pubA
/// .merge(with: pubB, pubC)
/// .sink { print("\($0)", terminator: " " )}
///
/// pubA.send(1)
/// pubB.send(40)
/// pubC.send(90)
/// pubA.send(2)
/// pubB.send(50)
/// pubC.send(100)
///
/// // Prints: "1 40 90 2 50 100"
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C>(with b: B, _ c: C) -> Publishers.Merge3<Self, B, C> where B : Publisher, C : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output
/// Combines elements from this publisher with those from three other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:_:)-48buc``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:_:)-16rcy``.
///
/// In this example, as ``Publisher/merge(with:_:_:)`` receives input from the upstream publishers, it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
/// let pubD = PassthroughSubject<Int, Never>()
///
/// cancellable = pubA
/// .merge(with: pubB, pubC, pubD)
/// .sink { print("\($0)", terminator: " " )}
///
/// pubA.send(1)
/// pubB.send(40)
/// pubC.send(90)
/// pubD.send(-1)
/// pubA.send(2)
/// pubB.send(50)
/// pubC.send(100)
/// pubD.send(-2)
///
/// // Prints: "1 40 90 -1 2 50 100 -2 "
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D>(with b: B, _ c: C, _ d: D) -> Publishers.Merge4<Self, B, C, D> where B : Publisher, C : Publisher, D : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output
/// Combines elements from this publisher with those from four other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:_:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:_:)-48buc``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:_:)-16rcy``.
///
/// In this example, as ``Publisher/merge(with:_:_:_:)`` receives input from the upstream publishers, it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
/// let pubD = PassthroughSubject<Int, Never>()
/// let pubE = PassthroughSubject<Int, Never>()
///
/// cancellable = pubA
/// .merge(with: pubB, pubC, pubD, pubE)
/// .sink { print("\($0)", terminator: " " ) }
///
/// pubA.send(1)
/// pubB.send(40)
/// pubC.send(90)
/// pubD.send(-1)
/// pubE.send(33)
/// pubA.send(2)
/// pubB.send(50)
/// pubC.send(100)
/// pubD.send(-2)
/// pubE.send(33)
///
/// // Prints: "1 40 90 -1 33 2 50 100 -2 33"
///
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E>(with b: B, _ c: C, _ d: D, _ e: E) -> Publishers.Merge5<Self, B, C, D, E> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output
/// Combines elements from this publisher with those from five other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:_:_:_:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:_:)-48buc``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:_:)-16rcy``.
///
/// In this example, as ``Publisher/merge(with:_:_:_:_:_:)`` receives input from the upstream publishers, it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
/// let pubD = PassthroughSubject<Int, Never>()
/// let pubE = PassthroughSubject<Int, Never>()
/// let pubF = PassthroughSubject<Int, Never>()
///
/// cancellable = pubA
/// .merge(with: pubB, pubC, pubD, pubE, pubF)
/// .sink { print("\($0)", terminator: " " ) }
///
/// pubA.send(1)
/// pubB.send(40)
/// pubC.send(90)
/// pubD.send(-1)
/// pubE.send(33)
/// pubF.send(44)
///
/// pubA.send(2)
/// pubB.send(50)
/// pubC.send(100)
/// pubD.send(-2)
/// pubE.send(33)
/// pubF.send(33)
///
/// //Prints: "1 40 90 -1 33 44 2 50 100 -2 33 33"
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - f: A sixth publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E, F>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Publishers.Merge6<Self, B, C, D, E, F> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output
/// Combines elements from this publisher with those from six other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:_:_:_:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:_:)-48buc``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:_:)-16rcy``.
///
/// In this example, as ``Publisher/merge(with:_:_:_:_:_:)`` receives input from the upstream publishers; it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
/// let pubD = PassthroughSubject<Int, Never>()
/// let pubE = PassthroughSubject<Int, Never>()
/// let pubF = PassthroughSubject<Int, Never>()
/// let pubG = PassthroughSubject<Int, Never>()
///
/// cancellable = pubA
/// .merge(with: pubB, pubC, pubD, pubE, pubE, pubG)
/// .sink { print("\($0)", terminator: " " ) }
///
/// pubA.send(1)
/// pubB.send(40)
/// pubC.send(90)
/// pubD.send(-1)
/// pubE.send(33)
/// pubF.send(44)
/// pubG.send(54)
///
/// pubA.send(2)
/// pubB.send(50)
/// pubC.send(100)
/// pubD.send(-2)
/// pubE.send(33)
/// pubF.send(33)
/// pubG.send(54)
///
/// //Prints: "1 40 90 -1 33 44 54 2 50 100 -2 33 33 54"
///
///
/// The merged publisher continues to emit elements until all upstream publishers finish.
/// If an upstream publisher produces an error, the merged publisher fails with that error.
///
/// - Parameters:
/// - b: A second publisher.
/// - c: A third publisher.
/// - d: A fourth publisher.
/// - e: A fifth publisher.
/// - f: A sixth publisher.
/// - g: A seventh publisher.
/// - Returns: A publisher that emits an event when any upstream publisher emits an event.
public func merge<B, C, D, E, F, G>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Publishers.Merge7<Self, B, C, D, E, F, G> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output
/// Combines elements from this publisher with those from seven other publishers, delivering an interleaved sequence of elements.
///
/// Use ``Publisher/merge(with:_:_:_:_:_:_:)`` when you want to receive a new element whenever any of the upstream publishers emits an element. To receive tuples of the most-recent value from all the upstream publishers whenever any of them emit a value, use ``Publisher/combineLatest(_:_:_:)-48buc``.
/// To combine elements from multiple upstream publishers, use ``Publisher/zip(_:_:_:)-16rcy``.
///
/// In this example, as ``Publisher/merge(with:_:_:_:_:_:_:)`` receives input from the upstream publishers, it republishes the interleaved elements to the downstream:
///
/// let pubA = PassthroughSubject<Int, Never>()
/// let pubB = PassthroughSubject<Int, Never>()
/// let pubC = PassthroughSubject<Int, Never>()
/// let pubD = PassthroughSubject<Int, Never>()
/// let pubE = PassthroughSubject<Int, Never>()
/// let pubF = PassthroughSubject<Int, Never>()
/// let pubG = PassthroughSubje