Swift 将发布者的擦除数组合并到 AnyCancellable 中

Swift Combine erase array of publishers into AnyCancellable

是否可以触发 return 一个 Publisher 的多个请求并且能够在没有 sink 的情况下取消它们?

我想将这些请求合并到一个可取消的引用中,或者尽可能在没有 sink 的情况下存储每个请求(代码如下)。这可能吗?

func fetchDetails(for contract: String) -> AnyPublisher<String, Error>

触发多个请求并存储

  @State var cancellable: Set<AnyCancellable> = []

    let promises = items.map {
      self.fetchFeed.fetchDetails(for: [=12=].contract)
    }
    
    Publishers.MergeMany(promises)
      .sink(receiveCompletion: { _ in }, receiveValue: { _ in }) // ** is this required?
      .store(in: &cancellable)

这实际上取决于 fetchDetails 创建发布者的操作。在您订阅之前,Apple 提供的几乎每个发布者都没有副作用。例如,以下发布者在您订阅它们之前没有副作用:

  • NSObject.KeyValueObservingPublisher(由NSObject.publisher(for:options:)
  • 返回
  • NotificationCenter.Publisher(由NotificationCenter.publisher(for:object:)
  • 返回
  • Timer.TimerPublisher(由Timer.publishe(every:tolerance:on:in:options:)
  • 返回
  • URLSession.DataTaskPublisher(由URLSession.dataTaskPublisher(for:)
  • 返回
  • JustEmptyFailSequence.Publisher 等同步发布者。

事实上,据我所知,唯一 对创建有副作用的发布者是 Future,它在创建时立即关闭。这就是为什么您会经常看到 Deferred { Future { ... } } 结构:避免直接的副作用。

因此,如果 fetchDetails 返回的发布者的行为与大多数发布者一样,您必须订阅它以产生任何副作用(例如实际通过网络发送请求)。