Skip to content

Commit

Permalink
[#515] Add asyn await to network layer
Browse files Browse the repository at this point in the history
  • Loading branch information
nkhanh44 committed Oct 2, 2023
1 parent 3dcd29b commit 670ef6b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
//

import Alamofire
import Combine

protocol NetworkAPIProtocol {

func performRequest<T: Decodable>(
_ configuration: RequestConfiguration,
for type: T.Type
) -> AnyPublisher<T, AFError>
) async throws -> T
}

extension NetworkAPIProtocol {
Expand All @@ -19,16 +18,29 @@ extension NetworkAPIProtocol {
session: Session,
configuration: RequestConfiguration,
decoder: JSONDecoder
) -> AnyPublisher<T, AFError> {
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)
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
//

import Alamofire
import Combine

final class NetworkAPI: NetworkAPIProtocol {

Expand All @@ -16,8 +15,8 @@ final class NetworkAPI: NetworkAPIProtocol {
func performRequest<T: Decodable>(
_ configuration: RequestConfiguration,
for type: T.Type
) -> AnyPublisher<T, AFError> {
request(
) async throws -> T {
try await request(
session: Session(),
configuration: configuration,
decoder: decoder
Expand Down

0 comments on commit 670ef6b

Please sign in to comment.