How to understand sink in swift Combine

Understanding Sink in Swift Combine

Sink is an operator in Swift Combine that allows you to subscribe to a Publisher and perform actions on the emitted elements. It is typically used at the end of a publisher chain to handle the publication's data.

Syntax:

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

Parameters:

  • receiveCompletion: A closure that will be called when the publisher completes, either normally or with an error.
  • receiveValue: A closure that will be called whenever the publisher emits a new value.

Value:

Returns an AnyCancellable object that can be used to cancel the subscription to the publisher.

Usage:

To use sink, you provide two closures as arguments: one for handling completion events, and one for handling value emissions. Here's an example:

let publisher = Just("Hello")
    .sink(
        receiveCompletion: { completion in
            print("Publisher completed with: \(completion)")
        },
        receiveValue: { value in
            print("Received value: \(value)")
        }
    )

In this example, the sink operator will print a message when the publisher completes, and it will print the emitted value whenever a new value is received.

Additional Parameters:

Sink also supports additional parameters that allow for further customization:

  • storeAsCancellableIn: Specifies an object to store the subscription as a Cancellable.
  • receiveCancel: A closure that will be called when the subscription is cancelled.
  • updateCurrentValue: A closure that will be called with the current value whenever a new value is emitted.

Example with Additional Parameters:

let publisher = Just("Hello")
    .sink(
        storeAsCancellableIn: mySubscriber,
        receiveValue: { value in
            // Process the value...
        }
    )

In this example, the subscription is stored in a variable called mySubscriber and can be cancelled later if needed.

Additional Notes:

  • The receiveCompletion closure is optional, and can be omitted if you are only interested in receiving values.
  • The receiveValue closure is required, and must consume all values emitted by the publisher.
  • Sink can be used multiple times on the same publisher, allowing for multiple subscriptions with different handlers.