Alamofire publishDecodable 不会向服务器发送请求,但 responseDecodable 会

Posted

技术标签:

【中文标题】Alamofire publishDecodable 不会向服务器发送请求,但 responseDecodable 会【英文标题】:Alamofire publishDecodable does not send request to server but responseDecodable does 【发布时间】:2021-05-31 06:00:32 【问题描述】:

这段代码不会导致在我的服务器上记录请求或打印结果。

AF.request(endpoint, method: .post, parameters: parameters, headers: nil)
            .validate().publishDecodable(type: Token.self, decoder: decoder).value().print()

但是,这样做:

AF.request(endpoint, method: .post, parameters: parameters, headers: nil)
            .validate().responseDecodable(of: Token.self, decoder: decoder)
                print($0)
            

如何修改前者以产生预期的结果?

【问题讨论】:

【参考方案1】:

您尚未订阅已发布的流,因此未发出请求。 Alamofire 的发布者很懒惰,这意味着他们只有在收到对结果的订阅后才会发出请求。您需要使用sink 或以其他方式订阅输出以发出请求。 Combine 中的.print() 是一个提供对流的洞察的运算符,它不订阅流。对于与您的其他示例等效的内容,请使用 .sink print($0) 并将令牌存储在某处。

【讨论】:

以上是关于Alamofire publishDecodable 不会向服务器发送请求,但 responseDecodable 会的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputData

出现错误:使用 Alamofire.playground 时没有这样的模块“Alamofire”

var 请求:Alamofire.Request?使用未声明类型的 Alamofire

值:(failure(Alamofire.AFError.explicitlyCancelled)) 使用 Alamofire 发布者时

使用方案 Alamofire watchOS 构建工作区 Alamofire 失败

iOS开发之Alamofire源码深度解析