Visualize Combine Magic with SwiftUI – Part 2

Operators, subscribing, and canceling in Combine

Kevin Cheng
Oct 23, 2019 · 3 min read
Photo by Aziz Acharki on Unsplash

Perform Combine Operations in our Playground

In the end of this chapter, we’ll have a list of Combine operators (map, filter, scan and dropFirst) in master/detail format. You’ll be able to select one of them and start subscribing and canceling at anytime.


Add value states

First, we add an additional stream and have them working side by side.

@State private var stream1Values: [String] = []@State private var stream2Values: [String] = []

Add disposable set

@State private var disposables = Set<AnyCancellable>()
publisher.sink {
}.store(in: &self.disposables)

Add publishers

Now, let’s take a look at the publishers.

let publisher = self.invervalValuePublisher()

Operator example: map

let mapPublisher = { (Int($0) ?? 0) * 2 }.map { String($0) }.eraseToAnyPublisher()

Operator example: scan

Simple, right? Now I can easily demonstrate another operator, scan, with this CombineScanStreamView.

let scanPublisher = { Int($0) ?? 0 }.scan(0) { $0 + $1 }.map { String($0) }

Organizing Combine Operators

Now that we know how to visualize Combine operators, we want to be able to organize them a little bit.

Make operator views general

Let me create another view named GenericCombineStreamView.

var comparingPublisher: (AnyPublisher<String, Never>) -> (AnyPublisher<String, Never>)
let comparingPublisher = self.comparingPublisher(publisher)
comparingPublisher.sink {
}.store(in: &self.disposables)

Put Together in SwiftUI List

Let’s put them together and add a few more operators.

func filterPublisher(publisher: AnyPublisher<String, Never>) -> AnyPublisher<String, Never> {
publisher.filter { $0 != "2" }.eraseToAnyPublisher()
func dropPublisher(publisher: AnyPublisher<String, Never>) -> AnyPublisher<String, Never> {

Next Chapter

We’ve successfully created a playground that’s extendable enough to present a list of single-operation streams. But what about multi-operation streams (e.g., map and then filter)? Or how about single-operation streams from multiple streams (e.g., merging two streams).

Better Programming

Advice for programmers.

Kevin Cheng

Written by

iOS engineer / entrepreneur / freelancer / San Francisco

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade