Hi,
I have an array of network requests signalProducers and each outputs a string and I would like to combine them into one signalProducer which output an array of string (convert [SignalProducer<String, NSError>]
into SignalProducer<[String], NSError>
)
I searched and found combineLatest
, but it results in a tuple. Is there any way to make it an array ? Thanks in advance.
SignalProducerProtocol.merge
and collect
should do the job.
@andersio But I want to preserve the ordering of the original array of signalProducers in the combined signalProducer. collect
looks like collecting the values in the order that events get fired.
@andersio I write it currently like
arrayOfSignalProducers.reduce(SignalProducer<[String], NSError>.init(value: [])) { (combined, s) in
return combined.combineLatestWith(s).map({ (arr, str) in
return arr + [str]
})
}
but it looks ugly
You can use the concatenation strategy instead, which would enforce the order. However, you should note that the starting of producer would be serialised too. If you need them to happen in parallel, you might need to use merge
and somehow reorder them eventually.
SignalProducer(values: [...]).flatten(.Concat).collect()
@andersio I'm sorry I didn't quit get it. Can you illustrate the flatten
approach a bit by some more concrete code ? And I'm using RAC4, should it be flatMap ? Thank you so much !
SignalProducer(values: [producerA, producerB, producerC]).flatten(.Concat)
would create a flattened producer, which starts & forward values of producerB
after producerA
completes, etc.
flatMap
is just a shorthand of map
+ flatten
.
Most helpful comment
SignalProducer(values: [producerA, producerB, producerC]).flatten(.Concat)
would create a flattened producer, which starts & forward values ofproducerB
afterproducerA
completes, etc.flatMap
is just a shorthand ofmap
+flatten
.