如果最后一个值与 Operator Combine 框架中之前的值相似,则忽略最后一个值

Ignore last value if it was similar to one before in, Operator Combine framework

我有一个已发布的布尔值 属性,然后我订阅了该发布者,每次布尔值更改时,我的发布者都会发送一个新值

@Published var booleanProperty: Bool = false
let subscription = $booleanProperty
     .sink { newBool in
        print(newBool)
     }

我的问题是,是否有 操作员 忽略发布值,如果它与最新的值相似。

like 发布者发送 [true,true,false,false] 我刚得到 [true,false]

你需要removeDuplicates:

let subscription = $booleanProperty
    .removeDuplicates()
    .sink { newBool in
        print(newBool)
    }

来自文档(强调我的):

Publishes only elements that don’t match the previous element.

[...]

Because the two-element memory considers only the current element and the previous element, the operator prints the final 0 in the example data since its immediate predecessor is 4.

let numbers = [0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 0]
cancellable = numbers.publisher
    .removeDuplicates()
    .sink { print("\([=11=])", terminator: " ") }
 
// Prints: "0 1 2 3 4 0"