Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 357
code-ninja-54321 Avatar asked Nov 29 '16 20:11

code-ninja-54321


Video Answer


1 Answers

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]"
like image 131
Charles Maria Avatar answered Nov 15 '22 05:11

Charles Maria