合并:将闭包转换为发布者

时间:2020-05-17 03:23:08

标签: ios closures swiftui combine publisher

如何转换:

func getResults(completion: ([Result]?, Error) -> Void)

进入

var resultsPublisher: AnyPublisher<[Result], Error>

只是一个方案,我怎么看(这种语法不存在):

var resultsPublisher: AnyPublisher<[Result], Error> {
  let publisher: AnyPublisher = ... // init
  getResults { results, error in
     guard let results = results else {
       publisher.produce(error: error) // this syntax doesn't exist
       return
     }

     publisher.produce(results: results)  // this syntax doesn't exist

  }

  return publisher
}

我需要这样做,因为某些3d派对SDK使用completion closures,并且我想为它们编写扩展名,以返回Publishers

1 个答案:

答案 0 :(得分:5)

答案是Future的发布商,其解释为matt

var resultsPublisher: AnyPublisher<[Result], Error> {
    // need deferred when want 
    // to start request only when somebody subscribes 
    // + without Deferred it's impossible to .retry() later
    Deferred { 
        Future { promise in
           self.getResults { results, error in
              guard let results = results else {
                 promise(.failure(error))
                 return
              }

              promise(.success(results))
           }
         }
    }
    .eraseToAnyPublisher()
}