1

I'm using RxSwift. I have an array of textfields that is dependent on which UI is visible; it could have 1, 3, or 4 textfields in the array.

Iterating over the array, I create signals for each of them that maps it to a boolean indicating if the field is valid.

let textFields: [UITextField] = ...
var signals: [Observable<Bool>] = []
textFields.forEach { tf in
     let sig = tf.rx_text
                 .map { string in
                        return string.length > 0
                 }
     signals.append(sig)
}

Usually, to combine multiple signals, I would use combineLatest which has multiple variations to take in a different number of arguments, which would generally look like this if I had three signals

_ = combineLatest(sig1, sig2, sig3) { $0 }
        .subscribeNext { [weak self] valid in
            self!.someButton.enabled = valid
        }
        .addDisposableTo(disposeBag)

Is there a way to combine signals when the number of signals being combined is unknown?

Alternatively, is there a way to write a function that has a variable number of generic arguments? I'm thinking this would be the starting point to write a function to combine multiple signals without knowing how many.

Chris
  • 7,270
  • 19
  • 66
  • 110

2 Answers2

1

I've come up with a generic solution that seems to be working, with the exception of properly accounting for the case of passing in an empty array.

func combineSignals<T>(signals: [Observable<T>], combine: (T,T)->T ) -> Observable<T> {
    assert (signals.count >= 1)
    guard signals.count >= 2 else { return signals[0] }

    var comb = combineLatest(signals[0], signals[1]) { combine($0) }
    for i in 2..<signals.count {
        comb = combineLatest(comb, signals[i]) { combine($0) }
    }
    return comb
}
Chris
  • 7,270
  • 19
  • 66
  • 110
0

I guess you can find the answer here

Actually In RxExaples I found a lot of answers. They are covering a lot of comon problems there

Serg Dort
  • 477
  • 2
  • 5