【发布时间】: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