使用代码并组合时会转换Alamofire响应
我想使用Alamofire查询我的后端,使用Alamofire的内置代码解析编码响应,然后从结果结构中发布摘录,以由我的API类的呼叫者消费。假设我从后端有一些JSON数据(简化,但显示了结构):
{
"total": 123,
"results": [
{"foo" : "bar"},
{"foo" : "baz"}
]
}
以及关联的Codable
结构
struct MyServerData: Codable {
let total: Int
let results: [Result]
}
struct Result: Codable {
let foo: String
}
我可以获得,分析,发布和订阅以下所有
func myAPI() -> DataResponsePublisher<MyServerData> {
return AF.request("https://backend/path")
.validate()
.publishDecodable(type: MyServerData.self)
}
myAPI()
.sink { response in /* Do stuff, e.g. update @State */ }
内容 :喜欢做的就是仅发布[结果]
数组。正确的方法是什么?我是否应该使用.ResponsedEcodable()
并创建一个新的Publisher(某种程度上 - .map()
?),返回[result] [result] .publisher
?
虽然我认为我了解基于反应/流的原理,但我的组合fu仍然很弱,而且我对一个发行商转变为另一个发行商没有明确的处理(我猜?),
谢谢!
I want to use Alamofire to query my backend, encode the response using Alamofire's built-in Codable parsing and then publish an extract from the resulting Struct to be consumed by the caller of my API class. Say I have some JSON data from my backend (simplified, but shows the structure):
{
"total": 123,
"results": [
{"foo" : "bar"},
{"foo" : "baz"}
]
}
and the associated Codable
Structs
struct MyServerData: Codable {
let total: Int
let results: [Result]
}
struct Result: Codable {
let foo: String
}
I can get, parse, publish, and subscribe all fine with the following:
func myAPI() -> DataResponsePublisher<MyServerData> {
return AF.request("https://backend/path")
.validate()
.publishDecodable(type: MyServerData.self)
}
myAPI()
.sink { response in /* Do stuff, e.g. update @State */ }
What I'd like to do is to publish just the [Result]
array. What's the correct approach to this? Should I use .responseDecodable()
and create a new publisher (somehow - .map()
?) that returns a [Result].publisher
?
While I think I understand the reactive/stream based principles my Combine-fu is still weak and I don't have a clear handle on the transformation of one publisher into another (I'm guessing?)
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了使用
MAP
之类的组合API外,Alamofire还向dataResponsePublisher
本身提供了两个发布者。.result()
从dataresponse
中提取结果
,并创建anypublisher&lt; result&lt; value,aferror&gt; ,, never gt; 。
.value()
从dataResponse
中提取value
,并创建一个故障发布者,anypublisher&lt; value,aferror&gt;
。因此,根据您想要的错误处理,这可能很简单:
In addition to using Combine API like
map
, Alamofire offers two publishers onDataResponsePublisher
itself..result()
extracts theResult
from theDataResponse
and creates anAnyPublisher<Result<Value, AFError>, Never>
..value()
extracts theValue
from theDataResponse
and creates a failable publisher,AnyPublisher<Value, AFError>
.So depending on what kind of error handling you want, this could be as simple as: