我想订阅一个BehaviorRelay <[object]>,并且无论何时添加或删除元素,我都想执行一些功能。
我使用了distinctUntilChange方法
BehaviorRelay<[object]>.asObservable().distinctUntilChanged{ $0.count != $1.count}.subscribe{....}
但是没有用。我该怎么办?我是否应该尝试使用其他主题或中继来实现此目的?
var objects = BehaviorRelay<[Object]>(value: [])
let disposeBag = DisposeBag()
objects.asObservable()
.subscribe(onNext: { (objects) in
//Do something only when appending or removing elements.
}).disposed(by: disposeBag)
//For example
let tempObj = objects.value
tempObj.append(newObj)
objects.accept(tempObj)//this will be called
tempObj.removeAll()
objects.accept(tempObj)//this will be called
tempObj.property = "Change Property"
objects.accept(tempObj)//this will NOT be called
答案 0 :(得分:0)
摘自文档:
- 参数比较器:计算键值的相等比较器。
我相信您应该使用==
运算符检查Equality。因此,就您而言,请尝试以下方式:
BehaviorRelay<[object]>
.asObservable()
.distinctUntilChanged{ $0.count == $1.count}
.subscribe{....}