0Pricing
Swift Academy · Lesson

Custom Publishers and Subscribers

Build your own Combine components.

Custom Publishers and Subscribers is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Beyond Built-in Publishers

Combine ships with many publishers, but sometimes you need to wrap a non-Combine API as a publisher, or consume values with precise backpressure control. That means implementing the Publisher and Subscriber protocols yourself.

The Publisher Protocol

A Publisher declares its Output and Failure types and implements receive(subscriber:), where it hands a subscription to the incoming subscriber.

protocol Publisher {
    associatedtype Output
    associatedtype Failure: Error
    func receive<S: Subscriber>(subscriber: S)
        where S.Input == Output, S.Failure == Failure
}

The Role of Subscription

When a subscriber attaches, the publisher creates a Subscription object. The subscription is the link that manages demand and delivers values. It conforms to Subscription, which extends Cancellable.

A Custom Subscription

The subscription stores the subscriber and responds to demand requests by emitting values.

final class CountSubscription<S: Subscriber>: Subscription
    where S.Input == Int {
    private var subscriber: S?
    private var current = 0

    init(subscriber: S) {
        self.subscriber = subscriber
    }

    func request(_ demand: Subscribers.Demand) {
        var remaining = demand
        while remaining > 0 {
            remaining -= 1
            remaining += subscriber?.receive(current) ?? .none
            current += 1
        }
    }

    func cancel() {
        subscriber = nil
    }
}

A Custom Publisher

The publisher simply creates the subscription and passes it to the subscriber via receive(subscription:).

struct CountPublisher: Publisher {
    typealias Output = Int
    typealias Failure = Never

    func receive<S: Subscriber>(subscriber: S)
        where S.Input == Int, S.Failure == Never {
        let subscription = CountSubscription(subscriber: subscriber)
        subscriber.receive(subscription: subscription)
    }
}

Understanding Demand

Backpressure is Combine's flow control. A subscriber requests a certain Demand, and the publisher must not send more values than requested. Returning demand from receive(_:) increases the allowance.

The Subscriber Protocol

A custom Subscriber implements three methods: it receives the subscription, then each value, then a completion.

protocol Subscriber {
    associatedtype Input
    associatedtype Failure: Error
    func receive(subscription: Subscription)
    func receive(_ input: Input) -> Subscribers.Demand
    func receive(completion: Subscribers.Completion<Failure>)
}

A Custom Subscriber

Here a subscriber requests two values up front, then one more for each value it receives, printing as it goes.

final class PrintSubscriber: Subscriber {
    typealias Input = Int
    typealias Failure = Never

    func receive(subscription: Subscription) {
        subscription.request(.max(2))
    }

    func receive(_ input: Int) -> Subscribers.Demand {
        print("Value:", input)
        return .max(1)
    }

    func receive(completion: Subscribers.Completion<Never>) {
        print("Done")
    }
}

Wrapping a Delegate API

A practical use of custom publishers is bridging a delegate or callback API into Combine, so legacy code becomes composable. You store the subscriber and forward delegate callbacks as receive(_:) calls.

Prefer Subjects When You Can

Implementing the protocols by hand is rarely necessary. For most bridging, a PassthroughSubject or CurrentValueSubject is far simpler — you just call send(_:).

let subject = PassthroughSubject<Int, Never>()

subject
    .sink { print($0) }
    .store(in: &cancellables)

subject.send(1)
subject.send(2)

When to Go Custom

Reach for custom Publisher/Subscriber implementations when you need:

  • Fine-grained backpressure control
  • To wrap a complex non-Combine source efficiently
  • Reusable, type-safe operators

Otherwise, subjects and built-in operators are the right tool.

Quick Check

Test your custom publisher knowledge.

Recap

You learned to implement Combine's core protocols:

  • Publisher creates a Subscription for each subscriber
  • The subscription honors Demand (backpressure)
  • Subscriber receives subscription, values, and completion
  • Prefer subjects for most bridging needs

Understanding these internals demystifies how all of Combine works.

Frequently asked questions

Is the “Custom Publishers and Subscribers” lesson free?

Yes — the full text of “Custom Publishers and Subscribers” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom Publishers and Subscribers”?

Build your own Combine components. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Publishers and Subscribers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Transforming and Combining Streams
  2. Schedulers and Threading
  3. Error Handling Operators
  4. Custom Publishers and Subscribers
← Back to Swift Academy