removeDuplicates(by:)
Publishes only elements that don’t match the previous element, as evaluated by a provided closure.
Declaration
func removeDuplicates(by predicate: @escaping (Self.Output, Self.Output) -> Bool) -> Publishers.RemoveDuplicates<Self>Parameters
- predicate:
A closure to evaluate whether two elements are equivalent, for purposes of filtering. Return
truefrom this closure to indicate that the second element is a duplicate of the first.
Return Value
A publisher that consumes — rather than publishes — duplicate elements.
Discussion
Use removeDuplicates(by:) to remove repeating elements from an upstream publisher based upon the evaluation of the current and previously published elements using a closure you provide.
Use the removeDuplicates(by:) operator when comparing types that don’t themselves implement Equatable, or if you need to compare values differently than the type’s Equatable implementation.
In the example below, the removeDuplicates(by:) functionality triggers when the x property of the current and previous elements are equal, otherwise the operator publishes the current Point to the downstream subscriber:
struct Point {
let x: Int
let y: Int
}
let points = [Point(x: 0, y: 0), Point(x: 0, y: 1),
Point(x: 1, y: 1), Point(x: 2, y: 1)]
cancellable = points.publisher
.removeDuplicates { prev, current in
// Considers points to be duplicate if the x coordinate
// is equal, and ignores the y coordinate
prev.x == current.x
}
.sink { print("\($0)", terminator: " ") }
// Prints: Point(x: 0, y: 0) Point(x: 1, y: 1) Point(x: 2, y: 1)