Intermediate Combine

Apr 13 2021 · Swift 5.3, macOS 11.1, Xcode 12.2

Part 1: Intermediate Combine

03. Managing Backpressure

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 02. Sharing Resources Next episode: 04. Mapping Errors

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

When a subscriber initially calls subscription.request, it specifies the maximum number of values it is willing to receive. If you take a look at the protocol description for subscriber, you'll see that the receive method returns a demand. In receive, you can adjust that max number of values it's willing to receive each time a new value is received. This allows you to dynamically manage backpressure. One thing to note however, is that the adjustment is additive. The new max is added to the current max. Also, the new max must be positive, meaning you can increase the value of max, but never decrease it. Let's take a look at this in an example. Start an example block and within it create an IntSubscriber class, which adopts subscriber. Make typialiases for the input and failure types. Then make the three variants of the receive function in the subscriber protocol. In the first one, call requests on the past tense subscription, sending the max to two. And the second receive function returned a new demand value based on the input value. Remember this max value is added off. In the final receive function which takes in the completion simply output a message to console. Initialize and intsubscriber, create a pass through subject that handles entered your data and never returns errors, and subscribe to that subject with subscriber. Same values to the subject to push them through the pipeline. Run this in a playground and you'll see that the first five values are admitted but the six is not. See why look at the value of Max in the second receive function. When the input is one, the new max is four the original max of two plus a new max of two. When the input is three, the new max is five the previous of four plus a new one. And for all other values, the max remains what it was which for the last entry is five.