Swift Combine-数组上的前缀发布者

问题描述 投票:0回答:1

我正在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)
swift combine split-apply-combine
1个回答
0
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.