7

I'm using ReactiveCocoa and I have several SignalProducers

let center = NSNotificationCenter.defaultCenter()
let signalProducer1 = center.rac_notification(name: notificationName1, object: nil)
let signalProducer2 = center.rac_notification(name: notificationName2, object: nil)
let signalProducer3 = center.rac_notification(name: notificationName3, object: nil)

I want to combine them into a single signal producer that produces a signal whenever one of them produces a signal.

At first the combineLatest function looked like a good solution

let combinedProducer = combineLatest(signalProducer1, signalProducer2, signalProducer3)

However, according to this article, the resulting producer only produces its first signal when all the three have produced a signal.

This interactive diagram shows exactly what I want, so I want to use the flatten function with the .Merge FlatteningStrategy. However, I'm having a hard time figuring out the syntax to achieve this.

bjornorri
  • 369
  • 1
  • 3
  • 11

2 Answers2

15

Update: RAC 4.2.1 and upwards

Due to changes in how flatten works we need to help the compiler an be more explicit about the types:

let s1: SignalProducer<Int, NSError> = ...
let s2: SignalProducer<Int, NSError> = ...
let s3: SignalProducer<Int, NSError> = ...


let _: SignalProducer<Int, NSError> =
    SignalProducer<SignalProducer<Int, NSError>, NSError>(values: [s1, s2, s3])
        .flatten(.Merge)

That becomes a bit cumbersome, so you might want to split it:

let producers: SignalProducer<SignalProducer<Int, NSError>, NSError> =
    SignalProducer(values: [s1, s2, s3])

let merged: SignalProducer<Int, NSError> = x.flatten(.Merge)

Thanks @Harry for the comment pointing the new version issue out.


RAC 4.2 and below

In RAC 4 this would be

let merged = SignalProducer(values: [signalProducer1, signalProducer2, signalProducer3])
  .flatten(.Merge)

At the moment Xcode 7.1.1 doesn't suggest .flatten in the autocompletion window, which might result in you (or just me) thinking it is not there, but if you type it all it will work.

mokagio
  • 16,391
  • 3
  • 51
  • 58
  • This no longer works with ReactiveCocoa 4.2.1 and above it seems – Harry Aug 25 '16 at 17:31
  • Sorry to go back on my previous comment, but this issue was actually fixed in 4.2.2. I believe the issue itself was introduced in 4.2.0. – Harry Aug 30 '16 at 10:50
  • 1
    Hi @Harry, I am still seeing the issue, and I'm actually using `master`, so what's going to be version 5.0. Any ideas? – mokagio Sep 13 '16 at 21:31
10

You can achieve that as follows:

let merged = SignalProducer(values: [ signalProducer1, signalProducer2, signalProducer3 ])
    |> flatten(.Merge)
ikesyo
  • 436
  • 3
  • 6