【问题标题】:Swift map from array of objects to array of async functions and await them allSwift 从对象数组映射到异步函数数组并等待它们
【发布时间】:2022-02-14 04:07:46
【问题描述】:

我刚刚更新到 Xcode 13.2.1,现在可以访问异步等待,我正在尝试找到可以从组合“转换”到异步等待的地方。

我想实现以下...

给定一个类型...

struct Person {
  let name: String

  func fetchAvatar(completion: @escaping (UIImage?) -> Void) {
    // fetch the image from the web and pass it into the completion.
  }
}

我目前有这样的功能...

func fetchAllTheAvatars(people: [Person], completion: ([UIImage]) -> Void) {
  Publisher.MergeMany(
    people.map { person in
      Future<UIImage?, Never> { promise in
        person.fetchAvatar { promise(.success($0)) }
      }
    }
  )
  .compactMap { $0 }
  .collect()
  .sink { completion($0) }
  .store(in: &cancellables )
}

现在...在我看来,这可能是转为使用 async await 和 AsyncSequence 的一个很好的候选者@也许...?!?不过,它不一定是理想的,我只是想了解如何使用它们。我习惯了 JS 和 TS 中的async await,这似乎有点不同。 :D

我向我的 Person 添加了一个包装函数...

func fetchAvatar() async -> UIImage? {
  await withCheckedContinuation { continuation in
    fetchAvatar { image in
      continuation.resume(returning: image)
    }
  }
}

但现在我被困在如何更新我的 fetchAllTheAvatars 函数上。

func fetchAllTheAvatars(people: [Person]) async -> [UIImage] {
  people.map { ...???... }
}

我在网上看到的所有地方似乎都使用for await line in url.lines { ... },但我还没有 AsyncSequence。我需要以某种方式将我的Person 的非异步数组“转换”为AsyncSequence 的() -&gt; Image?。

这可能吗?我这样做是不是完全错误的方式?

谢谢

【问题讨论】:

  • 您的组合代码不一定以与people 数组相同的顺序获取图像。这是故意的吗?
  • 我确定你已经看过WWDC video,但看起来你可以在你已有的方法的sink 中使用yield。
  • John Sundell 写了一堆helpful articles 关于 Swift Concurrency 以及其他将现有 API 迁移到 async/await 的文章。
  • @Sweeper 啊,我不知道,但在实际代码中,数据的顺序并不重要。不过谢谢,我以后会记住这一点的。 ??????????

标签: swift async-await


【解决方案1】:

标准模式是TaskGroup。为单个图像添加任务,然后在for 循环中添加await,map,或者在本例中为reduce:

func fetchAllTheAvatars(people: [Person]) async -> [Person.ID: UIImage] {
    await withTaskGroup(of: (Person.ID, UIImage?).self) { group in
        for person in people {
            group.addTask { await (person.id, person.fetchAvatar()) }
        }
        
        return await group.reduce(into: [Person.ID: UIImage]()) { (dictionary, result) in 
            if let image = result.1 {
                dictionary[result.0] = image
            }
        }
    }
}

请注意,由于无法保证顺序并且您的某些 Person 可能不会返回图像,因此我的实现会返回一个高效的、与顺序无关的结构(即字典)。

不用说,以上假设你使Person符合Identifiable:

struct Person: Identifiable {
    let id = UUID()
    let name: String
    
    func fetchAvatar() async -> UIImage? { … }
}

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2021-03-06
    • 2014-07-21
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    相关资源
    最近更新 更多