code-ninja-54321
code-ninja-54321

Reputation: 539

How to combine multiple SignalProducers?

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

Upvotes: 5

Views: 1696

Answers (1)

Charles Maria
Charles Maria

Reputation: 2195

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]"

Upvotes: 6

Related Questions