Skip to content

Latest commit

 

History

History
39 lines (34 loc) · 1.42 KB

README.md

File metadata and controls

39 lines (34 loc) · 1.42 KB

AsyncAwaitWrapper

Code

class AsyncAwaitWrapper<Resource, ResourceError> where ResourceError: Error {
    typealias ResourceLoader = (_ completion: @escaping (Result<Resource, ResourceError>) -> Void) -> Void
    let loader: ResourceLoader
    
    init(loader: @escaping ResourceLoader) {
        self.loader = loader
    }
    
    func load() async -> Result<Resource, ResourceError> {
        return await withCheckedContinuation { continuation in
            loader() { result in
                continuation.resume(returning: result)
            }
        }
    }
    
    func load() async throws -> Resource {
        try await withCheckedThrowingContinuation { continuation in
            loader() { result in
                switch result {
                case let .success(resource):
                    continuation.resume(returning: resource)
                    
                case let .failure(error):
                    continuation.resume(throwing: error)
                }
            }
        }
    }
}

How to use

  • Check provided composer with demonstration how to use.