Swift 转换为';[publisher.Map<;URLSession.DataTaskPublisher[ProductRep]?>;]';致[ProductRep]
如何计算flatMap、reduce等以将其转换为ProductRep数组 我当前得到的Swift 转换为';[publisher.Map<;URLSession.DataTaskPublisher[ProductRep]?>;]';致[ProductRep],swift,functional-programming,combine,Swift,Functional Programming,Combine,如何计算flatMap、reduce等以将其转换为ProductRep数组 我当前得到的无法将类型“publisher.Map”的值转换为关闭结果类型“StoreService.ProductRep”——因为我真的不知道如何将publisher.Map转换为实际内容。 这旨在成为使用map/flatMap的出版商和订阅者的更大网络的一部分 let mapResult: [ProductRep] = parsePageURIs(firstPage, jsonDict) .m
无法将类型“publisher.Map”的值转换为关闭结果类型“StoreService.ProductRep”
——因为我真的不知道如何将publisher.Map
转换为实际内容。
这旨在成为使用map/flatMap的出版商和订阅者的更大网络的一部分
let mapResult: [ProductRep] = parsePageURIs(firstPage, jsonDict)
.map { pageUri in self.importProductsPublisher(pageUri, urlSession: urlSession, firstPage: false) }
.map { publisher in publisher.map {(productsData, productsResponse) in
return self.handleImportProductsResponse(data: productsData, response: productsResponse, category: category, urlSession: urlSession)
}
}
func importProductsPublisher(_ uri: String, urlSession: URLSession, firstPage: Bool) -> URLSession.DataTaskPublisher { /* Start the network query */ }
func handleImportProductsResponse(data: Data, response: URLResponse, category: CategoryRep, urlSession: URLSession) -> [ProductRep]? { /* Handle the result of the network query and parse into an array of items (ProductRep) */ }
我认为这里发生了两件事。首先,您缺少某种类型的接收器,通常您会看到一个发布链以.sink或.assign结尾
whatever.map{ ... }.sink{ items in
//Do something with items in this closure
}
其次,您似乎正在将页面URI映射到发布者的集合,而不是单个发布者。然后在映射中有一个嵌套映射,它还不能解析任何内容
您可以使用其中一个合并发布服务器,如merge many和collect,将发布服务器从一个减少到多个:
一个基本的收集示例:
let arrayOfPublishers = (0...10).map{ int in
return Just(int)
}
Publishers.MergeMany(arrayOfPublishers).collect().sink { allTheInts in
//allTheInts is of type [Int]
print(allTheInts)
}
我想你需要这样的东西:
let productPublishers = parsePageURIs(firstPage, jsonDict).map { pageUri in
return self.importProductsPublisher(pageUri, urlSession: urlSession, firstPage: false).map {(productsData, productsResponse) in
return self.handleImportProductsResponse(data: productsData, response: productsResponse, category: category, urlSession: urlSession)
}
}
Publishers.MergeMany(productPublishers).collect().sink { products in
//Do somethings with the array of products
}
映射数据请求发布者后,将URI映射到发布者结果的模型中,然后使用MergeMany&collect将所有发布者合并到一个数组中,最后是实际触发所有事件的接收器。谢谢您的回答。我真的没有意识到基本上只有两个订阅者——我太习惯Scala风格的未来界面了。这本书有许多种类的作品。它确实合并流,但传播完成的消息。这意味着接收器只在第一个要完成的流上完成。我将研究一些合适的方法来处理这个问题……当我进行测试时,我发现如果我忽略了对
collect()
的调用,它将触发每个发布服务器的接收器,以防有帮助。是的,我相信你可以定制订户,但我还没有做到这一点,也没有觉得有必要这么做。还很早。