passthroughsubject in swift

PassthroughSubject is a type of Subject in Combine framework which shares similarity with CurrentValueSubject, but with a clear distinction in the way it takes and sends values. Here's an example of how to create and use a PassthroughSubject:

main.swift
import Combine

enum MyError: Error {
    case invalidValue
}

let subject = PassthroughSubject<String, MyError>()

// Subscribe to the PassthroughSubject
let subscription = subject.sink(
    receiveCompletion: { completion in
        switch completion {
        case .finished:
            print("Subscription completed successfully")
        case .failure(let error):
            print("Subscription failed with \(error)")
        }
    },
    receiveValue: { value in
        print("Received value: \(value)")
    })

// Send a value to the PassthroughSubject
subject.send("Hello, World!")

// Complete the PassthroughSubject
subject.send(completion: .finished)

// Cancel the subscription
subscription.cancel()
715 chars
31 lines

In the above example, we create a PassthroughSubject that publishes String values and error of type MyError. We then subscribe to the subject using the sink() operator which prints out the received completion and value events. Finally, we send a value and completion to the subject before canceling the subscription.

Note that unlike CurrentValueSubject, the PassthroughSubject doesn't have an initial value and doesn't store the most recently received value. When you subscribe to the PassthroughSubject, you only receive any subsequent values that are sent to it.

related categories

gistlibby LogSnag