Search code examples
iosswiftreactive-cocoareactive-swift

How do I bind a single SignalProducer to multiple UI components?


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.


Solution

  • 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