---
title: "tryRemoveDuplicates(by:)"
framework: combine
role: symbol
role_heading: Instance Method
path: "combine/publisher/tryremoveduplicates(by:)"
---

# tryRemoveDuplicates(by:)

Publishes only elements that don’t match the previous element, as evaluated by a provided error-throwing closure.

## Declaration

```swift
func tryRemoveDuplicates(by predicate: @escaping (Self.Output, Self.Output) throws -> Bool) -> Publishers.TryRemoveDuplicates<Self>
```

## Parameters

- `predicate`: A closure to evaluate whether two elements are equivalent, for purposes of filtering. Return true from this closure to indicate that the second element is a duplicate of the first. If this closure throws an error, the publisher terminates with the thrown error.

## Return Value

Return Value A publisher that consumes — rather than publishes — duplicate elements.

## Discussion

Discussion Use tryRemoveDuplicates(by:) to remove repeating elements from an upstream publisher based upon the evaluation of elements using an error-throwing closure you provide. If your closure throws an error, the publisher terminates with the error. In the example below, the closure provided to tryRemoveDuplicates(by:) returns true when two consecutive elements are equal, thereby filtering out 0, 1, 2, and 3. However, the closure throws an error when it encounters 4. The publisher then terminates with this error. struct BadValuesError: Error {} let numbers = [0, 0, 0, 0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] cancellable = numbers.publisher     .tryRemoveDuplicates { first, second -> Bool in         if (first == 4 && second == 4) {             throw BadValuesError()         }         return first == second     }     .sink(         receiveCompletion: { print ("\($0)") },         receiveValue: { print ("\($0)", terminator: " ") }      )

// Prints: "0 1 2 3 4 failure(BadValuesError()"

## See Also

### Filtering elements

- [filter(_:)](combine/publisher/filter(_:).md)
- [tryFilter(_:)](combine/publisher/tryfilter(_:).md)
- [compactMap(_:)](combine/publisher/compactmap(_:).md)
- [tryCompactMap(_:)](combine/publisher/trycompactmap(_:).md)
- [removeDuplicates()](combine/publisher/removeduplicates().md)
- [removeDuplicates(by:)](combine/publisher/removeduplicates(by:).md)
- [replaceEmpty(with:)](combine/publisher/replaceempty(with:).md)
- [replaceError(with:)](combine/publisher/replaceerror(with:).md)
