This is Understanding Combine, written by Matt Neuburg. It is a work in progress. 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 editions are iOS 13 Programming Fundamentals with Swift and Programming iOS 13. Thank you!


Filter

.filter (Publishers.Filter) takes a function (the filter function) that receives the published value from upstream and stops it from proceeding further down the pipeline unless it passes some test. The function returns a Bool saying whether the value should be permitted to proceed down the pipeline. Think of a filter as a map to nothing.

In this (rather silly) example, we’re running a Timer, but there’s also a UISwitch mySwitch in our interface, and if the UISwitch is off, no Timer firing signals get through the pipeline:

Timer.publish(every: 1, on: .main, in: .default)
    .autoconnect()
    .filter {_ in self.mySwitch.isOn}

There is also a .tryFilter (Publishers.TryFilter); it works similarly to .tryMap, so I won’t say more about it.


Table of Contents