Reactive Programming in iOS with Combine

Feb 4 2021 Swift 5.3, macOS 11.0, Xcode 12.2

Part 2: Transforming & Filtering Operators

10. Filtering Operators

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 9. Challenge: Create a Phone Number Lookup Next episode: 11. More Filtering Operators

This video was last updated on Feb 4 2021

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

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Filtering opertors consume values from a publisher, and conditionally decide whether to pass them onto the consumer. There are quite a few filtering operators to talk about, and even variations on those operators, so I’ve already run my own filtering operator to narrow them down to a set to go over here. Let’s get started with some filtering basics.

example(of: "filter") {
  // 1
  let numbers = (1...10).publisher

  // 2
  numbers
    .filter { $0.isMultiple(of: 3) }
    .sink(receiveValue: { n in
      print("\(n) is a multiple of 3!")
    })
    .store(in: &subscriptions)
}
example(of: "removeDuplicates") {
  // 1
  let words = "hey hey there! want to listen to mister mister ?"
                  .components(separatedBy: " ")
                  .publisher
  // 2
  words
    .removeDuplicates()
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)
}
example(of: "compactMap") {
  // 1
  let strings = ["a", "1.24", "3",
                 "def", "45", "0.23"].publisher

  // 2
  strings
    .compactMap { Float($0) }
    .sink(receiveValue: {
      // 3
      print($0)
    })
    .store(in: &subscriptions)
}
example(of: "ignoreOutput") {
  // 1
  let numbers = (1...10_000).publisher

  // 2
  numbers
    .ignoreOutput()
    .sink(receiveCompletion: { print("Completed with: \($0)") },
          receiveValue: { print($0) })
    .store(in: &subscriptions)
}