如果您在 Playgroud 中尝试此代码:
import Combine
import Foundation
struct User {
let name: String
}
private var subscriptions = Set<AnyCancellable>()
var didAlreadyImportUsers = false
var users = [User]()
func importUsers() -> Future<Bool, Never> {
Future { promise in
DispatchQueue.global(qos: .userInitiated).async {
sleep(5)
users = [User(name: "John"), User(name: "Jack")]
promise(.success(true))
}
}
}
func getUsers(age: Int? = nil) ->Future<[User], Error> {
Future { promise in
promise(.success(users))
}
}
var usersPublisher: AnyPublisher<[User], Error> {
if didAlreadyImportUsers {
return getUsers().eraseToAnyPublisher()
} else {
return importUsers()
.setFailureType(to: Error.self)
.combineLatest(getUsers())
.map { $0.1 }
.eraseToAnyPublisher()
}
}
usersPublisher
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { value in
print(value)
}).store(in: &subscriptions)
它将打印:
[]
finished
但我希望:
[User(name: "John"), User(name: "Jack")]
finished
如果我删除该行,sleep(5)
则它会正确打印结果。这似乎是一个异步问题。好像.combineLatest(getUsers())
不是在等importUsers()
我以为combineLatest
是在照顾那个?我在这里缺少什么?
(在我的真实代码中有一个长时间运行的核心数据操作,而不是sleep
)