2

I have a class with the Variable properties number and text and want to observe any changes done on both variables. The values of these properties are not needed.

In my real case I have more than 10 Variables to observe, so maybe it should be possible to pass them as an array of .asObservable().

let number: Variable<Int>

let text:   Variable<String>

func doSomethingWhenAnyValueWasChanged() {
    // some code
}

How do I achieve that?

I tried to do it with Observable.combineLatest() in multiple ways, but it didn't work out for me. Maybe I missed something?

SebKas
  • 342
  • 3
  • 19

1 Answers1

3

From the documentation it looks like Combine Latest would be your best option.

CombineLatest

when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function.

let number: Variable<Int>

let text:   Variable<String>

_ = Observable.combineLatest(number.asObservable(), text.asObservable()) { x, y in
       doSomethingWhenAnyValueWasChanged()
}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • And when I do the same, but passing the observables as an array, I get a compile error: `contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored` – SebKas May 02 '18 at 08:26
  • yeah i've just checked that in a playground, its just saying you need to use the variable name in the closure, like `{ x in }` or you could use `{ _ in }` if you dont need the variable – Scriptable May 02 '18 at 09:31
  • yes, this works, and I now found a way to pass Observers as an array: `Observable.combineLatest([number.asObservable().map { $0 as AnyObject}, text.asObservable().map { $0 as AnyObject } ])` (from [here](https://stackoverflow.com/questions/39050059/rxswift-merge-different-kind-of-observables)). But I really wish there would be a nicer way. – SebKas May 02 '18 at 09:47