【问题标题】:How to resolve two method calls with AnyPublisher return type into one?如何将 AnyPublisher 返回类型的两个方法调用解析为一个?
【发布时间】:2021-04-28 00:24:45
【问题描述】:

我有两个签名相同的方法func getItems() -> AnyPublisher<[Item], AppError>。 第一个是从存储中获取项目,第二个是从 Internet 获取。

如何将这样的逻辑添加到具有相同返回类型的第三个方法中,如果第一个方法成功完成我返回storage.getItems(),否则我返回network.getItems()

【问题讨论】:

    标签: ios swift combine


    【解决方案1】:

    如果在项目不存在时从storage.getItems() 返回的发布者出错,那么您可以“捕获”错误并改为发出新的发布者:

    func getItems() -> AnyPublisher<[Item], AppError> {
       storage.getItems()
           .catch { err in
                // check the err, if you need to
                network.getItems()
           }
           .eraseToAnyPublisher()
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2013-01-20
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多