合并框架(URLSession.DataTaskPublisher):使用发布者数组更改第一个发布者结果

时间:2020-07-22 09:20:08

标签: swift reactive-programming combine

我有一个通用的“执行”方法可以从网络上下载一些数据(省略了一些代码):

   func perform<D: Decodable>(_ endPoint: EndPoint) -> AnyPublisher<D, APIProviderError> {
      do {
         let request = try requestBuilder.build(with: endPoint)

         return try configurateSession(urlRequest: request, stub: endPoint.testData)
            .dataTaskPublisher(for: request)
            .decode(type: D.self, decoder: JSONDecoder())
      catch {
            fatalError(error.localizedDescription)
      }
}

  1. 最初,我加载主页结构。 json示例:
{
   "layout": {
      "id": "10",
      "slots": [
         {
            "slotNumber": 1,
            "widgets": [
               {
                  "id":"10",
                  "type": "booking"
               },
               {
                  "id": "11",
                    "type": "banners"
               },
               {
                  "id":"12",
                  "type": "chips"
               },
               {
                  "id":"13",
                  "type": "products"
               },
               {
                  "id": "15",
                    "type": "banners"
               }
   ]
}

并将其解析为结构数组

struct Container: Decodable {
   let layout: Layout
}

struct Layout: Decodable {
   let slots: [Slot]
}

struct Slot: Decodable {
   let widgets: [Section]
}

struct Section: Decodable  {
   private enum CodingKeys: String, CodingKey {
      case id, type
   }

   let id: String
   let type: SectionType
   var items: [Item]?
}

enum SectionType: String, Decodable {
   case banners, brands, products, orders, coupons, map, card, booking, chips
}
  1. 对于每个小部件(部分),根据其类型,我需要加载其项目并更改小部件。项目示例:

{
   "data": [
      {
         "offerPrice": "59.99",
         "name": "ss",
         "id": "60461"
      },
      {
         "offerPrice": "79.99",
         "name": "www",
         "id": "60750"
      }]
}

{
   "data": [
      {
         "image": "url"
      },
      {
         "image": "url",
         "categoryId": "3074457345616766223"
      }
      ]
   }

struct ItemContainer<T: Decodable>: Decodable {
   let id: String
   let items: [T]
}

class Banner: Item, Decodable {
   let categoryID: String?
   let infoID: String?
   let imageURL: String?
}

class Product: Item, Decodable {
   let id: String
   let name: String
   let offerPrice: String
}

我认为,对于每个小部件,都有必要创建一个发布者。我不知道下一步该怎么做。邮编不适用于收藏集

我写了以下内容:

      provider.perform(.structMain)
         .map { (container: Container) in
            container.layout.slots.first?.widgets
         }.eraseToAnyPublisher()
         .sink(receiveCompletion: { _ in

         }, receiveValue: { result in
          ????????
         })
         .store(in: &self.cancellableset)

或者我还需要其他东西

0 个答案:

没有答案