По сути, в вашей конкретной ситуации вы смотрите на что-то вроде этого:
func createIngredients(ingredients: [Ingredient]) -> AnyPublisher<[CreateIngredientMutation.Data], Error> {
let publisherOfPublishers = Publishers.Sequence<[AnyPublisher<CreateIngredientMutation.Data, Error>], Error>(sequence: ingredients.map(createIngredient))
return publisherOfPublishers.flatMap { $0 }.collect(ingredients.count).eraseToAnyPublisher()
}
Это зависит от того, что каждый из ваших внутренних издателей всегда дает ровно один результат - так что об этом нужно знать.
Более общий ответ, с помощью которого вы можете проверить его, используя EntwineTest framework :
import XCTest
import Combine
import EntwineTest
final class MyTests: XCTestCase {
func testCreateArrayFromArrayOfPublishers() {
typealias SimplePublisher = Publishers.Just<Int>
// we'll create our 'list of publishers' here
let publishers: [SimplePublisher] = [
.init(1),
.init(2),
.init(3),
]
// we'll turn our publishers into a sequence of
// publishers, a publisher of publishers if you will
let publisherOfPublishers = Publishers.Sequence<[SimplePublisher], Never>(sequence: publishers)
// we flatten our publisher of publishers into a single merged stream
// via `flatMap` then we `collect` exactly three results (we know we're
// waiting for as many results as we have original publishers), then
// return the resulting publisher
let finalPublisher = publisherOfPublishers.flatMap{ $0 }.collect(publishers.count)
// Let's test what we expect to happen, will happen.
// We'll create a scheduler to run our test on
let testScheduler = TestScheduler()
// Then we'll start a test. Our test will subscribe to our publisher
// at a virtual time of 200, and cancel the subscription at 900
let testableSubscriber = testScheduler.start { finalPublisher }
// we're expecting that, immediately upon subscription, our results will
// arrive. This is because we're using `just` type publishers which
// dispatch their contents as soon as they're subscribed to
XCTAssertEqual(testableSubscriber.sequence, [
(200, .subscription), // we're expecting to subscribe at 200
(200, .input([1, 2, 3])), // then receive an array of results immediately
(200, .completion(.finished)), // the `collect` operator finishes immediately after completion
])
}
}