2

I am using Swift, ReactiveSwift, and ReactiveCocoa.

Assuming I have a single SignalProducer, is there a way for multiple UI components to update when an Event is produced?

eg.

let sp = SignalProducer<Int, NoError> = // ...
label1.reactive.text <~ sp.map { String($0) }
label2.reactive.text <~ sp.map { "You entered \(String($0)) }

The issue I currently face is that the SignalProducer is started as soon as I use the <~ operator. As such, the producer is called twice. This isn't desirable when the producer is, say, a network request.

sdasdadas
  • 23,917
  • 20
  • 63
  • 148

2 Answers2

4

You could have a separate MutableProperty that gets bound to the SignalProducer, and have the two labels bind to that MutableProperty. If you don't want the 0 to show up, you could make the MutableProperty hold an optional Int

let sp = SignalProducer<Int, NoError> = // ...
let result = MutableProperty(0)
label1.reactive.text <~ result.map { String($0) }
label2.reactive.text <~ result.map { "You entered \(String($0)) }
result <~ sp
tkuichooseyou
  • 650
  • 1
  • 6
  • 16
2

I know this is old and already answered, but an alternative to using a Property is to use startWithSignal:

let sp: SignalProducer<Int, NoError> = // ...
sp.startWithSignal { (signal, _) in
    label1.reactive.text <~ signal.map { String($0) }
    label2.reactive.text <~ signal.map { "You entered \(String($0)) }
}
jjoelson
  • 5,771
  • 5
  • 31
  • 51