swift - 如何使用 combine 返回 fetch 调用的结果?
问题描述
我是新来的组合并且努力了解如何返回我的获取引脚的结果。
我可以将结果设置为,@Published
但我只想能够调用 fetch 方法并等待结果或错误。
class PinService: NSObject, ObservableObject {
private var session: Session
private var subscriptions = Set<AnyCancellable>()
init(session: Session) {
self.session = session
super.init()
}
func fetchPins (categories: Set<CategoryModel>, coordinates: CLLocationCoordinate2D) {
_fetchPins(categories: categories, coordinates: coordinates)
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("fetchPins() error")
case .finished:
print("fetchPins() complete")
}
}, receiveValue: { pins in
/*
What to do here?
I can add a @Published var pins: [Pin], and do
self.pins = pins
But if I want to be able to return the value or the error, how can I do that?
*/
})
.store(in: &self.subscriptions)
}
private func _fetchPins(categories: Set<CategoryModel>, coordinates: CLLocationCoordinate2D) -> Future<[Pin], Error> {
return Future<[Pin], Error> { promise in
let categoryIds = categories.map { return $0.id }.joined(separator: ",")
let radius = 15 //miles
self.session.request(baseUrl + "/api/v1/pinsRadius?latitude=\(coordinates.latitude)&longitude=\(coordinates.longitude)&radius=\(radius)&categories=\(categoryIds)")
.responseDecodable(of: [Pin].self) { (response: DataResponse) in
switch response.result {
case .success(let pins):
promise(.success((pins)))
case .failure(let error):
promise(.failure(error))
}
}
}
}
}
对不起,如果这是一个愚蠢的问题,谢谢。
解决方案
一种解决方案是在您的函数中使用完成处理程序并从receiveValue
func fetchPins (categories: Set<CategoryModel>,
coordinates: CLLocationCoordinate2D,
completion: @escaping (Result<[Pin], Error>) -> Void)) {
_fetchPins(categories: categories, coordinates: coordinates)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
completion(.failure(error))
print("fetchPins() error")
case .finished:
print("fetchPins() complete")
}
}, receiveValue: { pins in
completion(.success(pins))
})
.store(in: &self.subscriptions)
}
你的电话fetchPins
会看起来像
fetchPins(categories: someValue, coordinates: someOtherValue) { pins in
//do stuff with pins here
}
推荐阅读
- java - Maven依赖插件
- javascript - 获取 POST 请求保存数据,但在使用 Google 表单将数据保存到 Google 电子表格时返回 ok 作为 false
- reactjs - 无法重新导出 directory.js 中的组件
- google-apps-script - Highlight duplicates and copy to new sheet
- javascript - 有没有办法防止根据条件触发事件?
- clickhouse - 从 IDE DataGrip 连接到 ClickHouse 时出现“未知设置 session_id”
- javascript - 指定的值“NaN”无法解析,或者在 Jquery 中超出范围
- visual-studio - 为什么我的汇编代码在 Visual Studio 上显示错误消息?
- java - 段落中单词的频率
- python - place_ids:需要 API 吗?