【问题标题】:Executing 2 parallel network requests using Swift Combine使用 Swift Combine 执行 2 个并行网络请求
【发布时间】:2023-02-02 23:19:38
【问题描述】:

我正在尝试使用两个具有不同返回类型的不同发布者从两个不同端点加载数据。当两个请求都完成时,我需要更新 UI,但是两个请求也可能会失败,所以 Zip 不能解决问题。通常我会使用 DispatchGroup 来完成此操作,但我还没有弄清楚如何使用 Combine 来完成此操作。有没有办法将 DispatchGroup 与 Combine 一起使用?

let dispatchGroup: DispatchGroup = .init()
let networkQueue: DispatchQueue = .init(label: "network", cos: .userInitiated)

dispatchGroup.notify { print("work all done!" }

publisher
    .receive(on: networkQueue, options: .init(group: dispatchGroup)
    .sink { ... }
    .receiveValue { ... }
    .store(in: &cancellables)

publisher2
    .receive(on: networkQueue, options: .init(group: dispatchGroup)
    .sink { ... }
    .receiveValue { ... }
    .store(in: &cancellables)

立即执行通知。这不是正确的做法吗?

【问题讨论】:

标签: swift combine


【解决方案1】:

您需要使用 Publishers.CombineLatest,它将获取两个发布者并创建一个新的发布者,结果是最新的两个流的价值:

Publishers.CombineLatest(publisher, publisher2)
    // Receive values on the main queue (you decide whether you want to do this)
    .receive(on: DispatchQueue.main)
    .sink(receiveCompletion: { completion in
        // Handle error / completion
        // If either stream produces an error, the error will be forwarded in here
    }, receiveValue: { value1, value2 in
        // value1 will be the value of publisher's Output type
        // value2 will be the value of pubslier2's Output type
    })
    // You only need to store this subscription - not publisher and publisher2 individually
    .store(in: &cancellables)

Publishers.CombineLatest 发布者可以被视为等同于使用 DispatchGroup,您在其中为您启动的每个网络操作调用 dispatchGroup.enter()。但是,一个关键区别是 CombineLatest 发布者将产生多个值,如果任何发布者产生多个值。对于正常的网络操作,您无需担心这一点。但是,如果您发现自己处于只需要组合发布者生成的第一个或前 N 个值的情况,则可以使用 prefix(_:) 修饰符,这将确保您永远不会收到超过 N 个事件。

编辑:已更新以修复代码中的拼写错误。

【讨论】:

  • 这不编译。此外,我正在使用的合并了许多发布者的 value1,以及另一个网络发布者的 value2。我正在尝试连接 http 状态,即使一个发出多次而另一个发出 1 次
  • 你是对的,Publisher.CombineLatest 应该是 Publishers.CombineLatest - 这是一个错字?你能详细说明你实际需要实现的目标吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多