如何将 AnyPublisher<DataResponse<T, Error>、Never> 转换为 AnyPublisher<T, Error>

How to convert AnyPublisher<DataResponse<T, Error>, Never> to AnyPublisher<T, Error>

DataResponse是Alamofire的对象。它 returns Decodable 对象和 Error 本身在 .

中成功

要求是分别传递接收到的Decodable对象和ErrorAnyPublisher<DataResponse<T, Error>, Never>AnyPublisher<T, Error>是否可行.

T 视为任何数据类型对象。

func fetchDataViaAlamofire(usingURl url: String) -> AnyPublisher<T, Error> {
        return AF.request(url,
                          method: .get)
        .validate()
        .publishDecodable(type: T.self)
        .map { response in
            
            // ?
            // Cannot convert value of type 'DataResponse<T?, AFError>' to closure result type 'T'
            response.map { value in
                return response.value
            }
            
            // ?
            // Any way to convert AFError to Error in AnyPublisher<T, Error>
        }
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
        
    }

首先你必须在方法的签名中添加泛型参数T

AF提供了运算符.value()来进行类型转换。此外,您必须 map/cast AFErrorError

func fetchDataViaAlamofire<T: Decodable>(usingURL url: String) -> AnyPublisher<T, Error> {
    return AF.request(url, method: .get)
        .validate()
        .publishDecodable(type: T.self)
        .value()
        .mapError{[=10=] as Error}
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
}