【问题标题】:Swift Combine - prefix publisher on arraySwift Combine - 数组上的前缀发布者
【发布时间】:2020-01-23 13:16:21
【问题描述】:

我正在使用 Swift/Combine 中的发布者,我有一个函数可以获取 100 条记录并将它们作为数组返回。

作为测试,我只想返回前两项,但它并没有像我预期的那样工作,它总是返回 100,我的感觉是因为,第一项是 100 项的数组,如果是这样,如何拆分它们?

import UIKit
import Combine

struct Post : Decodable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

//let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!

var subscriptions: Set<AnyCancellable> = []

func fetch() -> AnyPublisher<[Post], Never> {
    return URLSession.shared.dataTaskPublisher(for: url)
        .tryCompactMap{ (arg) -> [Post]? in
            let (data, _) = arg
            return try JSONDecoder().decode([Post].self, from: data)
    }
        //.print("here")
        .replaceError(with: [])
        .eraseToAnyPublisher()
}

fetch()
    .prefix(2)
    .sink(receiveCompletion: { (comp) in
        print("comp: \(comp)")
    }) { (res) in
        print("Res: \(res.count)")
}.store(in: &subscriptions)

更新,这似乎有效,但不确定语法:

fetch()
.flatMap { Publishers.Sequence(sequence: $0) }
.prefix(2)
.sink(receiveCompletion: { (comp) in
  print("comp: \(comp)")
}) { (res) in
  print("Res: \(res)")
}.store(in: &subscriptions)

【问题讨论】:

  • 您使用flatMap 是正确的解决方案。您应该将其发布为答案。 (您可以回答自己的问题。)
  • @robmayoff 确实如此,但 .flatMap 仍然会产生大量数据。看看我的答案,如何解决这个问题。

标签: swift combine split-apply-combine


【解决方案1】:
.flatMap(maxPublishers: 2)

根据您想要完成的总体目标,对您来说可能是一种更好的方法。

【讨论】:

    【解决方案2】:

    您可以使用map 获取完整数组并仅提取您需要的内容。看看下面的例子:

    [Array(0..<100)].publisher.map { array in
      return Array(array[..<2])
    }.sink(receiveValue: { items in
      print(items)
    })
    

    这是一个发布者,发布一个包含 100 个值的数组。然后我使用array[..&lt;2] 创建一个包含前两项的ArraySlice。然后将该切片转换为Array,以便以后使用。

    sink 中收到的 items 参数是一个只有两个项目的数组。

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2020-11-06
      相关资源
      最近更新 更多