首页 > 解决方案 > 如何使用 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))
                    }
            }
        }
    }
}

对不起,如果这是一个愚蠢的问题,谢谢。

标签: swiftcombine

解决方案


一种解决方案是在您的函数中使用完成处理程序并从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
}

推荐阅读