Suppose I have a bunch of SignalProducers in an array:
[SignalProducer<Car, NSError>]
How do I combine them to get one SignalProducer that waits for all of them and gets all the Cars?
SignalProducer<[Car], NSError>
Use case: Do a network request to an endpoint http://cardatabase.com/:car_id for a bunch of car IDs and thus obtain multiple Car objects. The problem is that the URLSession function can only get a SignalProducer for one Car at a time. The question is how to combine many of them.
(Edit: Yikes, this reminds me a lot of sequenceA in Haskell. Can I do a similar thing in ReactiveSwift?)
Here's an example of how you can do this using flatten(_:) and reduce(_:, _:).
let firstProducer = SignalProducer<Int, NoError>(value: 0)
let secondProducer = SignalProducer<Int, NoError>(value: 1)
let thirdProducer = SignalProducer<Int, NoError>(value: 2)
SignalProducer<SignalProducer<Int, NoError>, NoError>(values: [firstProducer, secondProducer, thirdProducer])
.flatten(.merge)
.reduce([]) { $0 + [$1] }
.startWithValues { print($0) } //prints "[0, 1, 2]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With