Instance Method

sink(receiveCompletion:receiveValue:)

Attaches a subscriber with closure-based behavior.

Declaration

func sink(receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void), receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable

Parameters

receiveCompletion

The closure to execute on completion. If nil, the sink uses an empty closure.

receiveValue

The closure to execute on receipt of a value. If nil, the sink uses an empty closure.

Return Value

A subscriber that performs the provided closures upon receiving values or completion.

Discussion

Use sink(receiveCompletion:receiveValue:) to observe values received by the publisher and process them using a closure you specify.

In this example, a Range publisher publishes integers to a sink(receiveCompletion:receiveValue:) operator’s receiveValue closure that prints them to the console. Upon completion the 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

See Also

Connecting Simple Subscribers

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

Assigns each element from a publisher to a property on an object.

func sink(receiveValue: ((Self.Output) -> Void)) -> AnyCancellable

Attaches a subscriber with closure-based behavior to a publisher that never fails.