简体   繁体   English

Swift 5.5 异步等待方法到 AnyPublisher

[英]Swift 5.5 async await method to AnyPublisher

I am trying to call a Swift 5.5 async throws method inside a method that should return an AnyPublisher but I am having trouble to achieve this.我试图在应该返回 AnyPublisher 的方法中调用 Swift 5.5 async throws 方法,但我无法实现这一点。 I tried using a Future (promise) which did not work and I only managed to find a Swift 5.5 API to convert closure based methods to async ones.我尝试使用一个不起作用的Future (promise),我只设法找到一个 Swift 5.5 API 将基于闭包的方法转换为异步方法。

class Loader {

    func loadSomeData() -> async throws [String] {
        /// some code
    }
}

class Service {
   let loader: Loader
   init(loader: Loader) { 
      self.loader = loader
   }

   func someDataPublisher() -> AnyPublisher<[String], Error> {
       // How can I convert this?
       try await loader.loadSomeData() 
   }
}
class Service {
   let loader: Loader
   init(loader: Loader) {
      self.loader = loader
   }

   func someDataPublisher() -> AnyPublisher<[String], Error> {
       return Deferred { [loader] in
           Future { promise in
               async {
                   do {
                       promise(.success(try await loader.loadSomeData()))
                   } catch {
                       promise(.failure(error))
                   }
               }
           }
       }
       .eraseToAnyPublisher()
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM