Skip to content

Instantly share code, notes, and snippets.

@kimxwan0319
Last active August 3, 2023 12:44
Show Gist options
  • Save kimxwan0319/c13d11efb7c3f4582d43ee11675e5b26 to your computer and use it in GitHub Desktop.
Save kimxwan0319/c13d11efb7c3f4582d43ee11675e5b26 to your computer and use it in GitHub Desktop.
Moya+Concurrency

CODE

import Foundation

import Moya

extension MoyaProvider {
    
    class MoyaConcurrency {
        
        private let provider: MoyaProvider
        private let jsonDecoder = JSONDecoder()
        
        init(provider: MoyaProvider) {
            self.provider = provider
        }
        
        func request<T: Decodable>(_ target: Target) async throws -> T {
            return try await withCheckedThrowingContinuation { continuation in
                provider.request(target) { result in
                    switch result {
                    case .success(let response):
                        guard let res = try? self.jsonDecoder.decode(T.self, from: response.data) else {
                            continuation.resume(throwing: MoyaError.jsonMapping(response))
                            return
                        }
                        continuation.resume(returning: res)
                    case .failure(let error):
                        continuation.resume(throwing: error)
                    }
                }
            }
        }
    }
    
    var async: MoyaConcurrency {
        MoyaConcurrency(provider: self)
    }
    
}

Usage

class MyAPI {
      private let provider = MoyaProvider<MyTarget>()
      
     func home() async throws -> HomeResponse {
        return try await provider.async.request(.home)
    }
}

출처: Moya/Moya#2265 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment