0

How do I trigger one block of code whenever any of a set of SignalProducers change? In other words, how do I get rid of my current redundant code:

property1.producer.startWithValues { (value) in 
    // do stuff with property1.value and property2.value
}

property2.producer.startWithValues { (value) in 
    // do the same stuff with property1.value and property2.value
}
ozool
  • 94
  • 1
  • 9
  • Can you add a bit of context? For example, does the code block use both properties' values or only the value that gets a passed in to the closure? – jjoelson Sep 22 '17 at 20:37
  • Sorry, the block uses both property's values. I've modified the above to clarify. – ozool Sep 23 '17 at 03:06

2 Answers2

0

You can save the block of code as a variable, then you would simply assign that variable to property1.producer.startWithValues.

esreli
  • 4,993
  • 2
  • 26
  • 40
  • You mean save the block as a variable, and then use it in both places? It seems like there should be a way to have a single block run when either property changes.. Some way to say "if either property changes, run this block"... – ozool Sep 23 '17 at 03:07
0

You can use combineLatest to create a new property that contains both values:

let prop = property1.combineLatest(with: property2)
prop.producer.startWithValues { (val1, val2) in
    // do stuff here
}

If either value changes, the block will be triggered.

jjoelson
  • 5,771
  • 5
  • 31
  • 51