简体   繁体   English

如何使用RxSwift观察数组中的值

[英]How to observe the value in array with RxSwift

There is class have a Bool property 有班有布尔的财产

class Coupon: NSObject {
    var invalid: Bool = false
}

I create a array [Coupon],I need to modify the coupon.invalid to true one by one.when all of these coupon.invalid == true ,then I can process next task,How can I implement this logic with RxSwift ?Please help me ~~ 我创建一个数组[Coupon],我需要将coupon.invalid一次修改为true。当所有这些coupon.invalid == true时,我就可以处理下一个任务,如何使用RxSwift实现此逻辑?帮帮我~~

First you make your Coupon type a struct instead of a class. 首先,使Coupon类型成为结构而不是类。

struct Coupon {
    var invalid = false
}

And embed your array into a Variable. 并将您的数组嵌入变量中。

let coupons = Variable<[Coupon]>([])
coupons.value = getAllTheCoupons()

Now you can create an observable that emits a value whenever all the values are true. 现在,您可以创建一个可观察值,每当所有值都为true时便会发出一个值。

let allTrue = coupons.asObservable()
    .map { coupons in
        coupons.contains(where: { $0.invalid == false }) == false
    }
    .filter { $0 }

allTrue.subscribe(onNext: { _ in
    print("process next task.")
}).disposed(by: bag)

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

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