简体   繁体   中英

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.

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

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)) }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM