Swift Combine: Как создать одного издателя из списка издателей? - PullRequest
1 голос
/ 27 июня 2019

Используя новую платформу Combine от Apple, я хочу сделать несколько запросов от каждого элемента в списке.Тогда я хочу получить один результат от сокращения всех ответов.В основном я хочу перейти от списка издателей к одному издателю, который содержит список ответов.

Я пытался составить список издателей, но я не знаю, как свести этот список к одному.издатель.И я пытался создать издателя, содержащего список, но я не могу отобразить список издателей на плоскости.

Пожалуйста, посмотрите на функцию "createIngredients"

    func createIngredient(ingredient: Ingredient) -> AnyPublisher<CreateIngredientMutation.Data, Error> {
        return apollo.performPub(mutation: CreateIngredientMutation(name: ingredient.name, optionalProduct: ingredient.productId, quantity: ingredient.quantity, unit: ingredient.unit))
        .eraseToAnyPublisher()
    }

    func createIngredients(ingredients: [Ingredient]) -> AnyPublisher<[CreateIngredientMutation.Data], Error> {
        // first attempt
        let results = ingredients
            .map(createIngredient)
        // results = [AnyPublisher<CreateIngredientMutation.Data, Error>]

        // second attempt
        return Publishers.Just(ingredients)
            .eraseToAnyPublisher()
            .flatMap { (list: [Ingredient]) -> Publisher<[CreateIngredientMutation.Data], Error> in
                return list.map(createIngredient) // [AnyPublisher<CreateIngredientMutation.Data, Error>]
        }
    }

Я неубедитесь, как взять массив издателей и преобразовать его в издатель, содержащий массив.

Значение результата типа '[AnyPublisher]' не соответствует типу результата закрытия 'Издатель'

1 Ответ

3 голосов
/ 27 июня 2019

По сути, в вашей конкретной ситуации вы смотрите на что-то вроде этого:

    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
        ])
    }
}
...