Reactive Programming in iOS with Combine, Episode 10: Filtering Operators | Kodeco, the new raywenderlich.com

Basic filtering operators like filter, removeDuplicates, ignoreOutput and compactMap can be used to narrow down which values get sent downstream to subscribers.


This is a companion discussion topic for the original entry at https://www.kodeco.com/5429795-reactive-programming-in-ios-with-combine/lessons/10

Itโ€™s worth noting that removeDuplicate only removes duplicated elements when they are right next to each other, which surprised me.

example(of: "removeDuplicates()") {
  [
    "a",
    "b",
    "b", // <- This is a duplicate, it won't go through.
    "c",
    "b" // <- We've seen "b" already, however, the last element
    // wasn't "b", so this is not considered to be a duplicate
    // so it will go through.
  ]
    .publisher
    .removeDuplicates()
    .collect()
    .sink { print($0) } // <- Prints ["a", "b", "c", "b"]
    .store(in: &subscriptions)
}

Googling around, it seems that removeDuplicate is an equivalent to DistinctUntilChanged from Rx.

Combine doesnโ€™t see the items it receives as an array, but more like a stream (which potentially could be endless). So removeDuplicates just looks at the prior element, the name could be kind of misleading, but the documentation states: Publishes only elements that donโ€™t match the previous element.

1 Like