简体   繁体   中英

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 ~~

First you make your Coupon type a struct instead of a class.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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