gpt4 book ai didi

ios - 如何忽略RxSwift上的behaviorRelayRelay元素?

转载 作者:行者123 更新时间:2023-12-01 18:35:36 24 4
gpt4 key购买 nike

我正在观察BehaviorRelay,并且仅在项目数量增加时才想订阅。我尝试了distinct / dinstinctUntilChanged ,但它不符合我的需求,因为它将跳过太多或太少的次数。

behaviorRelay
.compactMap { $0?.items }
.subscribe(onNext: { elements in
print("items has one more element.")
}).disposed(by: bag)
var behaviorRelay = BehaviorRelay<[Car]?>(value: [])
class Car {
var items: [Any] // whatever... just an example.
}

最佳答案

首先,使用map从数组映射到数字(元素):

.map { $0?.count ?? 0 } // return 0 if array is nil

比使用 scan检索当前元素和上一个元素,如下所示:

.scan((0, 0)) { previousPairOfValues, newValue in
return (previousPairOfValues.1, newValue) // create new pair from newValue and second item of previous pair
}

然后使用 filter,仅传递递增的值:

.filter { $0.1 > $0.0 } // newer value greater than older value

而不是将其映射回最新值:

.map { $0.1 }

放在一起:

behaviorRelay
.compactMap { $0?.items }
.map { $0?.count ?? 0 } // return 0 if array is nil
.scan((0, 0)) { previousPairOfValues, newValue in
return (previousPairOfValues.1, newValue) // create new pair from newValue and second item of previous pair
}
.filter { $0.1 > $0.0 } // newer value greater than older value
.map { $0.1 }
.subscribe(onNext: { elementCount in
print("items has one more element.")
print("there are \(elementCount) items now")
}).disposed(by: bag)

关于ios - 如何忽略RxSwift上的behaviorRelayRelay元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59815298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com