From 670ef6bf55b77120df4fe930d6b108e4edaf17d3 Mon Sep 17 00:00:00 2001 From: nkhanh44 Date: Mon, 2 Oct 2023 17:01:11 +0700 Subject: [PATCH] [#515] Add asyn await to network layer --- .../NetworkAPI/Core/NetworkAPIProtocol.swift | 38 ++++++++++++------- .../Sources/Data/NetworkAPI/NetworkAPI.swift | 5 +-- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/Core/NetworkAPIProtocol.swift b/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/Core/NetworkAPIProtocol.swift index fb6a161d..ff17c8a9 100644 --- a/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/Core/NetworkAPIProtocol.swift +++ b/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/Core/NetworkAPIProtocol.swift @@ -3,14 +3,13 @@ // import Alamofire -import Combine protocol NetworkAPIProtocol { func performRequest( _ configuration: RequestConfiguration, for type: T.Type - ) -> AnyPublisher + ) async throws -> T } extension NetworkAPIProtocol { @@ -19,16 +18,29 @@ extension NetworkAPIProtocol { session: Session, configuration: RequestConfiguration, decoder: JSONDecoder - ) -> AnyPublisher { - return session.request( - configuration.url, - method: configuration.method, - parameters: configuration.parameters, - encoding: configuration.encoding, - headers: configuration.headers, - interceptor: configuration.interceptor - ) - .publishDecodable(type: T.self, decoder: decoder) - .value() + ) async throws -> T { + try await withCheckedThrowingContinuation { continuation in + session.request( + configuration.url, + method: configuration.method, + parameters: configuration.parameters, + encoding: configuration.encoding, + headers: configuration.headers, + interceptor: configuration.interceptor + ) + .response { response in + switch response.result { + case let .success(data): + do { + let decodedData = try decoder.decode(T.self, from: data ?? Data()) + continuation.resume(returning: decodedData) + } catch { + continuation.resume(throwing: error) + } + case let .failure(error): + continuation.resume(throwing: error) + } + } + } } } diff --git a/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/NetworkAPI.swift b/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/NetworkAPI.swift index 413a003c..d52c2081 100644 --- a/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/NetworkAPI.swift +++ b/Tuist/Interfaces/UIKit/Sources/Data/NetworkAPI/NetworkAPI.swift @@ -3,7 +3,6 @@ // import Alamofire -import Combine final class NetworkAPI: NetworkAPIProtocol { @@ -16,8 +15,8 @@ final class NetworkAPI: NetworkAPIProtocol { func performRequest( _ configuration: RequestConfiguration, for type: T.Type - ) -> AnyPublisher { - request( + ) async throws -> T { + try await request( session: Session(), configuration: configuration, decoder: decoder