简体   繁体   English

在RxCocoa / RxSwift中,如何观察BehaviorRelay <[object]>数组大小已更改

[英]In RxCocoa/RxSwift, how to observe BehaviorRelay<[object]> array size changed

I'd like to subscribe to a BehaviorRelay<[object]>, and I'd like to execute some functions whenever we append or remove elements. 我想订阅一个BehaviorRelay <[object]>,并且无论何时添加或删除元素,我都想执行一些功能。

I've used the distinctUntilChange method 我已经使用了distinctUntilChange方法

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. 我相信您应该使用==运算符检查Equality。 So, in your case, try this way: 因此,在您的情况下,请尝试以下方式:

BehaviorRelay<[object]>
    .asObservable()
    .distinctUntilChanged{ $0.count == $1.count}
    .subscribe{....}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM