ReactiveCocoa combine SignalProducers into one

对着背影说爱祢 提交于 2019-12-04 06:20:59

You can achieve that as follows:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!