小编And*_*era的帖子

Swift Combine: How to create a single publisher from a list of publishers?

使用Apple的新的Combine框架,我希望从列表中的每个元素发出多个请求。然后,我希望减少所有响应得到一个结果。基本上,我想从发布者列表转到拥有响应列表的单个发布者。

我尝试列出发布者列表,但是我不知道如何将列表缩小为一个发布者。而且我尝试过使发布者包含一个列表,但是我无法平面映射发布者列表。

请查看“ 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>]
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不确定如何获取发布者数组并将其转换为包含数组的发布者。

类型“ [AnyPublisher]”的结果值与关闭结果类型“ Publisher”不符

swift combine

6
推荐指数
2
解决办法
1518
查看次数

标签 统计

combine ×1

swift ×1