[英]In RxCocoa/RxSwift, how to observe BehaviorRelay<[object]> array size changed
我想訂閱一個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
從文檔:
- 參數比較器:計算鍵值的相等比較器。
我相信您應該使用==
運算符檢查Equality。 因此,在您的情況下,請嘗試以下方式:
BehaviorRelay<[object]>
.asObservable()
.distinctUntilChanged{ $0.count == $1.count}
.subscribe{....}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.