0

I'm having array of Bool Observables in Rxswift.

let rxBoolObservableArray: [Observable<Bool>] = [Observable<Bool>]()

Now, How to get If any of the element is false?

mohsin
  • 530
  • 5
  • 24

2 Answers2

2
func containsFalse(array: [Observable<Bool>]) -> Observable<Bool> {
    return Observable.combineLatest(array) { $0.contains(false) }
}

The combineLatest function will subscribe to all the observables in the array.

The above will also update the array every time one of the observables updates its value so the output will always be correct. The accepted answer doesn't do that (it only works for the Observable.just function and is incorrect.)

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
1

Here is allSatisfy extension based on @DanielT answer. It might be suitable for your problem:

extension Array where Iterator.Element: ObservableType {

    func allSatisfy(_ predicate: @escaping (Iterator.Element.E) throws -> Bool) -> Observable<Bool> {
        return Observable.combineLatest(self) { try $0.allSatisfy(predicate) }
    }
}

example usage:

rxBoolObservableArray
    .allSatisfy { $0 } // { $0 == true }
    .subscribe(onNext: { areTestsPassing in
        print(areTestsPassing)
    })
    .disposed(by: disposeBag) 
Tomasz Pe
  • 696
  • 7
  • 19
  • 1
    I don't think the `rethrows` is necessary since Observables emit an error event rather than throwing. – Daniel T. Feb 08 '19 at 02:37