I'd like to subscribe to a BehaviorRelay<[object]>, and I'd like to execute some functions whenever we append or remove elements.
I've used the distinctUntilChange method
BehaviorRelay<[object]>.asObservable().distinctUntilChanged{ $0.count != $1.count}.subscribe{....}
But didn't work. What should I try? Should I try using other Subjects or Relays to achieve this purpose?
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
From documentation:
- parameter comparer: Equality comparer for computed key values.
I believe you should check the Equality with ==
operator. So, in your case, try this way:
BehaviorRelay<[object]>
.asObservable()
.distinctUntilChanged{ $0.count == $1.count}
.subscribe{....}