简体   繁体   中英

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. 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.

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()
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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