Skip to Content
Course content

86: Operators: map, filter, combineLatest

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this a lot when developers first move toward reactive programming in Swift. They understand the concept of a "stream," but they treat the sink (the end of the pipeline) like a giant do { ... } block where all the business logic lives. It works, but it's brittle and hard to test.

Logic Leaking Into the Sink

// A common, messy approach to a search feature
searchTermsPublisher
    .combineLatest(filterEnabledPublisher)
    .sink { term, isEnabled in
        // 🚩 The "Everything-in-the-Sink" mistake
        if term.count >= 3 && isEnabled {
            let request = SearchRequest(query: term, active: isEnabled)
            self.apiClient.execute(request)
        } else {
            print("Search criteria not met")
        }
    }

If you're looking at this and thinking, "But it works," you're right. It does. But the sink is now doing three different jobs: it's filtering out short strings, checking a toggle state, and transforming a string into a request object. This is exactly where bugs hide. If you decide later that "Search" should also depend on a category selection, your sink becomes a nested nightmare of if-else statements.

Refining the Stream with Filter and Map

The goal of operators like filter and map is to ensure that by the time the data reaches your sink, it is already "correct." The sink should only be responsible for the final side effect—in this case, calling the API.

First, we use filter. This acts as a gatekeeper. If the condition isn't met, the data simply stops moving down the pipe. No else block is needed because the rest of the chain just doesn't execute. Then, we use map to transform the raw values into the object the API actually needs.

searchTermsPublisher
    .filter { $0.count >= 3 } // Only let valid strings through
    .combineLatest(filterEnabledPublisher)
    .filter { _, isEnabled in isEnabled } // Only let through if toggle is ON
    .map { term, _ in 
        return SearchRequest(query: term, active: true) 
    }
    .sink { request in
        // Now the sink is clean. It just does one thing.
        self.apiClient.execute(request)
    }

Merging Dependencies with combineLatest

You might be wondering why I used combineLatest instead of something like zip. This is a crucial distinction. zip requires a pair—it waits for both publishers to emit a new value before it sends anything. If the user types ten characters but never touches the "Filter Enabled" toggle, zip would stay silent.

combineLatest is different. Once every publisher in the group has emitted at least one value, it will fire every time any of them change. This is exactly what you want for UI state. If the user changes the toggle, you want the search to potentially trigger immediately using the last known search term.

One thing to watch out for: combineLatest won't emit anything until all participating publishers have sent at least one value. If your filterEnabledPublisher doesn't have an initial value (like a CurrentValueSubject), your search will feel broken because the first few keystrokes will be ignored until that toggle is flipped for the first time.




📋 Practical Task

Building a Reactive Form Validator

You are building a registration form. The "Create Account" button should only be enabled when the following conditions are met:

  • The email address contains an "@" symbol.
  • The password is at least 8 characters long.
  • The "Terms of Service" checkbox is checked (true).

Your Task: Create a pipeline using combineLatest, map, and filter (or boolean logic within a map) that takes three publishers—emailPublisher, passwordPublisher, and tosPublisher—and emits a single Boolean value to a sink that updates the submitButton.isEnabled property.

Avoid putting if/else logic inside the sink. The sink should only contain one line: self.submitButton.isEnabled = isValid.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.