【发布时间】:2021-02-27 03:39:03
【问题描述】:
我目前正在为我的 SwiftUI 项目使用 Moya alpha 15 和 Combine Framework。使用 Moya,我有一个负责创建请求的提供程序。
我想要什么:
- 使用 getInstance(page: Int) 获取我的初始 instanceResponseList 对象。
- 从该 instanceResponseList 对象,检查每个实例是否 hasChildren == true
- 如果 hasChildren == true,则使用实例的 id 调用 getInstanceChildren(id: String)
- 来自 getInstanceChildren(id: String) 的响应将被映射并分配给孩子:[Instance] 属性(response.data.instances)
这可能吗?如果没有,有没有更好的方法来做到这一点?
我想做什么:
我需要在 tableView 中使用来自 Instance 的 profileURL 显示个人资料图片。每个单元格的高度将是动态的,并且基于每个图像的纵横比。每个单元格可以有 1 + 个孩子的个人资料图像,排列方式不同。
我的服务调用和数据模型的一些示例代码:
public struct InstanceResponseList: Codable {
public var success: Bool
public var data: InstanceResponse
}
public struct InstanceResponse: Codable {
public var instances: [Instance]
public var hasMore: Bool //for pagination
}
public struct Instance: Codable {
public var id: String
public var profileURL: String?
public var hasChildren: Bool
public var children: [Instance] // I want to make a request and append the children for each of my instances.
enum CodingKeys: String, CodingKey {
case id = "instance_id"
case profileURL = "profile_url"
case hasChildren = "has_children"
}
}
public func getInstance(page: Int) -> AnyPublisher<InstanceResponseList, MoyaError> {
return instanceProvider
.requestPublisher(.allInstances(page: page, show: 10)) // page & show are parameters used for pagination, not relevant here
.map(InstanceResponseList.self)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
public func getInstanceChildren(id: String) -> AnyPublisher<InstanceResponseList, MoyaError> {
return haptagramProvider
.requestPublisher(.children(id: id))
.map(InstanceResponseList.self)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
我的尝试:
public func getInstanceWithChildren(page: Int) -> AnyPublisher<[Instance], MoyaError> {
return getInstance(page: Int)
.flatMap { instanceResponseList -> AnyPublisher<Instance, MoyaError> in
Publishers.Sequence(sequence: instanceResponseList.data.instances).eraseToAnyPublisher()
}
.flatMap { instance -> AnyPublisher<Instance, MoyaError> in
return getInstanceChildren(id: instance.id).map {
let instance = instance
instance.children = $0
return instance
}
.eraseToAnyPublisher()
}
.collect()
.eraseToAnyPublisher()
}
返回AnyPublisher<[Instance], MoyaError>,但我希望返回AnyPublisher<InstanceResponseList, MoyaError>。
【问题讨论】:
-
这能回答你的问题吗? Combine framework: how to process each element of array asynchronously before proceeding... 简而言之,在
getInstance之后使用flatMap以返回getInstanceChildren -
@NewDev 我认为这与我正在寻找的类似,但不同之处在于我需要降低一个级别才能从我的
getInstance。我该如何处理? -
“降低一个级别”正是我链接到的问题/答案所解决的问题
-
@NewDev:我尝试更新了我的问题。我对Combine还是很陌生,不是很熟悉。如果你能看看我是否做得对,将不胜感激。谢谢!
标签: ios swift reactive-programming combine moya