Swift Combine: removeDuplicates(), you can totally misuse it if you don’t read this.
Let’s learn about removeDuplicates(). As the name suggests, it removes the duplicates. But it works in a little bit different way that you might expect.
Applying removeDuplicates() — this is not what you expect
let words = ["apple", "apple", "fruit", "apple", "mango", "watermelon", "apple"]
words.publisher
.removeDuplicates()
.sink {
print($0) // apple, fruit, apple, mango, watermelon, apple
}
For this example, I prepared an array. You can see now apple appeared four times in the string. Obviously, apple
is duplicate.
But the result is completely the opposite of what you have expected!
Duplicate values still remain…
Only second element of the duplicate element apple
is removed...
Why is that?
In reactive programming, everything is coming to you as a sequence of that event.
If two different events are coming and if they are the same exact value Apple in this case, it is going to start removing those duplicates.
Conclusion and Warning!!!
removeDuplicate()
works only when the same value appears consecutively.