Protocol

Publisher

Declares that a type can transmit a sequence of values over time.

Declaration

protocol Publisher

Overview

A publisher delivers elements to one or more Subscriber instances. The subscriber’s Input and Failure associated types must match the Output and Failure types declared by the publisher. The publisher implements the receive(subscriber:) method to accept a subscriber. After this, the publisher can call the following methods on the 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.

  • receive(_:): Delivers one element from the publisher to the 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 map(_:) operator returns an instance of Publishers.Map.

Rather than implementing Publisher on your own, you can use one of several types provided by the Combine framework. For example, you can use an AnySubject instance and publish new elements imperatively with its send(_:) method. You can also add the @Published annotation to any property to give it a publisher that returns an instance of Published, which emits an event every time the property’s value changes.

Topics

Declaring Publisher Topography

A publisher must declare the output type of elements it produces and the type of failure (if any) that may terminate publishing.

associatedtype Output

The kind of values published by this publisher.

Required.

associatedtype Failure

The kind of errors this publisher might publish.

Required.

Working with Subscribers

func receive<S>(subscriber: S)

Attaches the specified subscriber to this publisher.

Required.

func subscribe<S>(S)

Attaches the specified subscriber to this publisher.

func subscribe<S>(S) -> AnyCancellable

Attaches the specified subject to this publisher.

Mapping Elements

func map<T>((Self.Output) -> T) -> Publishers.Map<Self, T>

Transforms all elements from the upstream publisher with a provided closure.

func tryMap<T>((Self.Output) -> T) -> Publishers.TryMap<Self, T>

Transforms all elements from the upstream publisher with a provided error-throwing closure.

func flatMap<T, P>(maxPublishers: Subscribers.Demand, (Self.Output) -> P) -> Publishers.FlatMap<P, Self>

Transforms all elements from an upstream publisher into a new or existing publisher.

func mapError<E>((Self.Failure) -> E) -> Publishers.MapError<Self, E>

Converts any failure from the upstream publisher into a new error.

func replaceNil<T>(with: T) -> Publishers.Map<Self, T>

Replaces nil elements in the stream with the proviced element.

func scan<T>(T, (T, Self.Output) -> T) -> Publishers.Scan<Self, T>

Transforms elements from the upstream publisher by providing the current element to a closure along with the last value returned by the closure.

func tryScan<T>(T, (T, Self.Output) -> T) -> Publishers.TryScan<Self, T>

Transforms elements from the upstream publisher by providing the current element to an error-throwing closure along with the last value returned by the closure.

func setFailureType<E>(to: E.Type) -> Publishers.SetFailureType<Self, E>

Changes the failure type declared by the upstream publisher.

Filtering Elements

func filter((Self.Output) -> Bool) -> Publishers.Filter<Self>

Republishes all elements that match a provided closure.

func tryFilter((Self.Output) -> Bool) -> Publishers.TryFilter<Self>

Republishes all elements that match a provided error-throwing closure.

func compactMap<T>((Self.Output) -> T?) -> Publishers.CompactMap<Self, T>

Calls a closure with each received element and publishes any returned optional that has a value.

func tryCompactMap<T>((Self.Output) -> T?) -> Publishers.TryCompactMap<Self, T>

Calls an error-throwing closure with each received element and publishes any returned optional that has a value.

func removeDuplicates() -> Publishers.RemoveDuplicates<Self>

Publishes only elements that don’t match the previous element.

func replaceEmpty(with: Self.Output) -> Publishers.ReplaceEmpty<Self>

Replaces an empty stream with the provided element.

func replaceError(with: Self.Output) -> Publishers.ReplaceError<Self>

Replaces any errors in the stream with the provided element.

Reducing Elements

func collect() -> Publishers.Collect<Self>

Collects all received elements, and emits a single array of the collection when the upstream publisher finishes.

func collect(Int) -> Publishers.CollectByCount<Self>

Collects up to the specified number of elements, and then emits a single array of the collection.

func collect<S>(Publishers.TimeGroupingStrategy<S>, options: S.SchedulerOptions?) -> Publishers.CollectByTime<Self, S>

Collects elements by a given strategy, and emits a single array of the collection.

enum Publishers.TimeGroupingStrategy

A strategy for collecting received elements.

func ignoreOutput() -> Publishers.IgnoreOutput<Self>

Ingores all upstream elements, but passes along a completion state (finished or failed).

func reduce<T>(T, (T, Self.Output) -> T) -> Publishers.Reduce<Self, T>

Applies a closure that accumulates each element of a stream and publishes a final result upon completion.

func tryReduce<T>(T, (T, Self.Output) -> T) -> Publishers.TryReduce<Self, T>

Applies an error-throwing closure that accumulates each element of a stream and publishes a final result upon completion.

Applying Mathematical Operations on Elements

func count() -> Publishers.Count<Self>

Publishes the number of elements received from the upstream publisher.

func max() -> Publishers.Comparison<Self>

Publishes the maximum value received from the upstream publisher, after it finishes.

func max(by: (Self.Output, Self.Output) -> Bool) -> Publishers.Comparison<Self>

Publishes the maximum value received from the upstream publisher, using the provided ordering closure.

func tryMax(by: (Self.Output, Self.Output) -> Bool) -> Publishers.TryComparison<Self>

Publishes the maximum value received from the upstream publisher, using the provided error-throwing closure to order the items.

func min() -> Publishers.Comparison<Self>

Publishes the minimum value received from the upstream publisher, after it finishes.

func min(by: (Self.Output, Self.Output) -> Bool) -> Publishers.Comparison<Self>

Publishes the minimum value received from the upstream publisher, after it finishes.

func tryMin(by: (Self.Output, Self.Output) -> Bool) -> Publishers.TryComparison<Self>

Publishes the minimum value received from the upstream publisher, using the provided error-throwing closure to order the items.

Applying Matching Criteria to Elements

func contains(Self.Output) -> Publishers.Contains<Self>

Publishes a Boolean value upon receiving an element equal to the argument.

func contains(where: (Self.Output) -> Bool) -> Publishers.ContainsWhere<Self>

Publishes a Boolean value upon receiving an element that satisfies the predicate closure.

func tryContains(where: (Self.Output) -> Bool) -> Publishers.TryContainsWhere<Self>

Publishes a Boolean value upon receiving an element that satisfies the throwing predicate closure.

func allSatisfy((Self.Output) -> Bool) -> Publishers.AllSatisfy<Self>

Publishes a single Boolean value that indicates whether all received elements pass a given predicate.

func tryAllSatisfy((Self.Output) -> Bool) -> Publishers.TryAllSatisfy<Self>

Publishes a single Boolean value that indicates whether all received elements pass a given error-throwing predicate.

Applying Sequence Operations to Elements

func drop<P>(untilOutputFrom: P) -> Publishers.DropUntilOutput<Self, P>

Ignores elements from the upstream publisher until it receives an element from a second publisher.

func drop(while: (Self.Output) -> Bool) -> Publishers.DropWhile<Self>

Omits elements from the upstream publisher until a given closure returns false, before republishing all remaining elements.

func dropFirst(Int) -> Publishers.Drop<Self>

Omits the specified number of elements before republishing subsequent elements.

func tryDrop(while: (Self.Output) -> Bool) -> Publishers.TryDropWhile<Self>

Omits elements from the upstream publisher until an error-throwing closure returns false, before republishing all remaining elements.

func append<S>(S) -> Publishers.Concatenate<Self, Publishers.Sequence<S, Self.Failure>>

Appends a Publisher’s output with the specified sequence.

func append<P>(P) -> Publishers.Concatenate<Self, P>

Appends this publisher’s output with the elements emitted by the given publisher.

func prepend<S>(S) -> Publishers.Concatenate<Publishers.Sequence<S, Self.Failure>, Self>

Prefixes a Publisher’s output with the specified sequence.

func prepend<P>(P) -> Publishers.Concatenate<P, Self>

Prefixes this publisher’s output with the elements emitted by the given publisher.

func prefix(Int) -> Publishers.Output<Self>

Republishes elements up to the specified maximum count.

func prefix(while: (Self.Output) -> Bool) -> Publishers.PrefixWhile<Self>

Republishes elements while a predicate closure indicates publishing should continue.

func prefix<P>(untilOutputFrom: P) -> Publishers.PrefixUntilOutput<Self, P>

Republishes elements until another publisher emits an element.

func tryPrefix(while: (Self.Output) -> Bool) -> Publishers.TryPrefixWhile<Self>

Republishes elements while a error-throwing predicate closure indicates publishing should continue.

Selecting Specific Elements

func first() -> Publishers.First<Self>

Publishes the first element of a stream, then finishes.

func first(where: (Self.Output) -> Bool) -> Publishers.FirstWhere<Self>

Publishes the first element of a stream to satisfy a predicate closure, then finishes.

func tryFirst(where: (Self.Output) -> Bool) -> Publishers.TryFirstWhere<Self>

Publishes the first element of a stream to satisfy a throwing predicate closure, then finishes.

func last() -> Publishers.Last<Self>

Only publishes the last element of a stream, after the stream finishes.

func last(where: (Self.Output) -> Bool) -> Publishers.LastWhere<Self>

Publishes only the last element of a stream that satisfies a predicate closure, after the stream finishes.

func tryLast(where: (Self.Output) -> Bool) -> Publishers.TryLastWhere<Self>

Publishes only the last element of a stream that satisfies an error-throwing predicate closure, after the stream finishes.

func output(at: Int) -> Publishers.Output<Self>

Publishes a specific element, indicated by its index in the sequence of published elements.

func output<R>(in: R) -> Publishers.Output<Self>

Publishes elements specified by their range in the sequence of published elements.

Combining Elements from Multiple Publishers

func merge(with: Self) -> Publishers.MergeMany<Self>

Combines elements from this publisher with those from another publisher of the same type, delivering an interleaved sequence of elements.

func merge<P>(with: P) -> Publishers.Merge<Self, P>

Combines elements from this publisher with those from another publisher, delivering an interleaved sequence of elements.

func merge<B, C>(with: B, C) -> Publishers.Merge3<Self, B, C>

Combines elements from this publisher with those from two other publishers, delivering an interleaved sequence of elements.

func merge<B, C, D>(with: B, C, D) -> Publishers.Merge4<Self, B, C, D>

Combines elements from this publisher with those from three other publishers, delivering an interleaved sequence of elements.

func merge<B, C, D, E>(with: B, C, D, E) -> Publishers.Merge5<Self, B, C, D, E>

Combines elements from this publisher with those from four other publishers, delivering an interleaved sequence of elements.

func merge<B, C, D, E, F>(with: B, C, D, E, F) -> Publishers.Merge6<Self, B, C, D, E, F>

Combines elements from this publisher with those from five other publishers, delivering an interleaved sequence of elements.

func merge<B, C, D, E, F, G>(with: B, C, D, E, F, G) -> Publishers.Merge7<Self, B, C, D, E, F, G>

Combines elements from this publisher with those from six other publishers, delivering an interleaved sequence of elements.

func merge<B, C, D, E, F, G, H>(with: B, C, D, E, F, G, H) -> Publishers.Merge8<Self, B, C, D, E, F, G, H>

Combines elements from this publisher with those from seven other publishers, delivering an interleaved sequence of elements.

func zip<P>(P) -> Publishers.Zip<Self, P>

Combine elements from another publisher and deliver pairs of elements as tuples.

func zip<P, Q>(P, Q) -> Publishers.Zip3<Self, P, Q>

Combine elements from two other publishers and deliver groups of elements as tuples.

func zip<P, Q, R>(P, Q, R) -> Publishers.Zip4<Self, P, Q, R>

Combine elements from three other publishers and deliver groups of elements as tuples.

Handling Errors

func assertNoFailure(String, file: StaticString, line: UInt) -> Publishers.AssertNoFailure<Self>

Raises a fatal error when its upstream publisher fails, and otherwise republishes all received input.

func `catch`<P>((Self.Failure) -> P) -> Publishers.Catch<Self, P>

Handles errors from an upstream publisher by replacing it with another publisher.

func retry(Int) -> Publishers.Retry<Self>

Attempts to recreate a failed subscription with the upstream publisher using a specified number of attempts to establish the connection.

Adapting Publisher Types

func switchToLatest() -> Publishers.SwitchToLatest<Self.Output, Self>

Flattens the stream of events from multiple upstream publishers to appear as if they were coming from a single stream of events.

Controlling Timing

func measureInterval<S>(using: S, options: S.SchedulerOptions?) -> Publishers.MeasureInterval<Self, S>

Measures and emits the time interval between events received from an upstream publisher.

func delay<S>(for: S.SchedulerTimeType.Stride, tolerance: S.SchedulerTimeType.Stride?, scheduler: S, options: S.SchedulerOptions?) -> Publishers.Delay<Self, S>

Delays delivery of all output to the downstream receiver by a specified amount of time on a particular scheduler.

func throttle<S>(for: S.SchedulerTimeType.Stride, scheduler: S, latest: Bool) -> Publishers.Throttle<Self, S>

Publishes either the most-recent or first element published by the upstream publisher in the specified time interval.

func timeout<S>(S.SchedulerTimeType.Stride, scheduler: S, options: S.SchedulerOptions?, customError: (() -> Self.Failure)?) -> Publishers.Timeout<Self, S>

Terminates publishing if the upstream publisher exceeds the specified time interval without producing an element.

Creating Reference-type Publishers

func share() -> Publishers.Share<Self>

Returns a publisher as a class instance.

Encoding and Decoding

func decode<Item, Coder>(type: Item.Type, decoder: Coder) -> Publishers.Decode<Self, Item, Coder>

Decodes the output from upstream using a specified TopLevelDecoder. For example, use JSONDecoder.

func encode<Coder>(encoder: Coder) -> Publishers.Encode<Self, Coder>

Encodes the output from upstream using a specified TopLevelEncoder. For example, use JSONEncoder.

Performing Type-Erasure

Specifying Schedulers

func subscribe<S>(on: S, options: S.SchedulerOptions?) -> Publishers.SubscribeOn<Self, S>

Specifies the scheduler on which to perform subscribe, cancel, and request operations.

func receive<S>(on: S, options: S.SchedulerOptions?) -> Publishers.ReceiveOn<Self, S>

Specifies the scheduler on which to receive elements from the publisher.

Adding Explicit Connectability

func makeConnectable() -> Publishers.MakeConnectable<Self>

Creates a connectable wrapper around the publisher.

Connecting Simple Subscribers

func assign<Root>(to: ReferenceWritableKeyPath<Root, Self.Output>, on: Root) -> AnyCancellable

Assigns the value of a KVO-compliant property from a publisher.

Instance Methods

Relationships

Conforming Types

See Also

Publishers

enum Publishers

A namespace for types that serve as publishers.

Beta
struct AnyPublisher

A type-erasing publisher.

Beta
protocol ConnectablePublisher

A publisher that provides an explicit means of connecting and canceling publication.

Beta
struct Published

The publisher for properties published by using an attribute.

Beta
protocol Cancellable

A protocol indicating that an activity or action supports cancellation.

Beta
class AnyCancellable

A type-erasing cancellable object that executes a provided closure when canceled.

Beta

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software