This is Understanding Combine, written by Matt Neuburg. Corrections and suggestions are greatly appreciated (you can comment here). So are donations; please consider keeping me going by funding this work at http://www.paypal.me/mattneub. Or buy my books: the current (and final) editions are iOS 15 Programming Fundamentals with Swift and Programming iOS 14. Thank you!


Understanding Combine

by Matt Neuburg

Introducing Combine

Unifying Asynchronicitywhat Combine is all about

Publish and Subscribethe heart of the Combine architecture

Introducing Operatorstransformations between publisher and subscriber

Pipelinesat last, some practical Combine examples!

Stopping a Pipelinecancel and AnyCancellable; finished completions

Failuresfailure completions; transmutation of failures; Never

Typesgeneric Output and Failure types

Summary

Subscribers

Sink

Assign

AnyCancellableretaining the subscriber with store

One-Shot Subscribersretaining the subscriber without store

Custom Subscribersthe Subscriber protocol

Publishers

Notification Center Publisherreceiving notifications

Data Task PublisherURLSession downloads

Future and Deferredturn any asynchronous code into a publisher

Timer Publisherrepeated intervals; also, connect and autoconnect

Key–Value Observing Publisheruse it wherever you were already using KVO

Publisheda better KVO

SubjectPassthroughSubject and CurrentValueSubject; Subject as subscriber

Value PublishersJust, Optional, Result, Sequence, Empty, Fail

Recordencapsulate the whole output of a pipeline

Custom Publishersthe Publisher protocol; the Subscription protocol

Operators

Transformers and Blockerschange the value or stop it

Maptransform a value

Scantransform a value based on the previous value

Filterto block or not to block

RemoveDuplicatesblock based on the previous value

CompactMapnil means block

FlatMapproducing a publisher within the pipeline; AnyPublisher; serializing asynchronicity; failing without terminating; exerting backpressure

SwitchToLatesta cousin of flatMap

No Valuesblock all values (ignoreOutput), and its opposite (replaceEmpty)

Accumulatorscapture values and wait

Partitionerssubranges

Joinersmany publishers, one subscriber

Splittersone publisher, many subscribers; more about Subjects

Timersplaying with time

Delaywait a while

Debouncewait for a pause

Timeoutnot too slow

Throttlenot too fast

MeasureIntervalhow long was that?

Buffersmoothe out timing differences

Error Handlerstransforming failures

MapErrorturn one error into another

ReplaceErrorturn failure into success

SetFailureTypeturn Never into failure

Catchturn failure into anything you like

Retryturn failure into try again

Codablesencode and decode

Threadersreceive(on:) and subscribe(on:)

WrapperseraseToAnyPublisher and makeConnectable

Debuggersfigure out how your pipeline works

Composed Operatorsmaking an operator, the easy way

Custom Operatorsmaking an operator, the hard way

Tricks and Tips