-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathNetworkService+Async.swift
77 lines (64 loc) · 2.4 KB
/
NetworkService+Async.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// File.swift
//
//
// Created by Lukas Schmidt on 19.12.21.
//
import Foundation
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension NetworkService {
/**
Fetches a resource asynchronously from remote location. Execution of the requests starts immediately.
**Example**:
```swift
let networkService: NetworkService = //
let resource: Resource<String> = //
let (result, response) = try await networkService.request(resource)
```
- parameter resource: The resource you want to fetch.
- returns: a touple containing the parsed result and the HTTP response
- Throws: A `NetworkError`
*/
@discardableResult
func request<Result>(_ resource: Resource<Result>) async throws -> (Result, HTTPURLResponse) {
var task: NetworkTask?
let cancel = { task?.cancel() }
return try await withTaskCancellationHandler(operation: {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation({ coninuation in
task = request(resource: resource, onCompletionWithResponse: {
coninuation.resume(with: $0)
})
})
}, onCancel: {
cancel()
})
}
/**
Fetches a resource asynchronously from remote location. Execution of the requests starts immediately.
**Example**:
```swift
let networkService: NetworkService = //
let resource: ResourceWithError<String, CustomError> = //
let (result, response) = try await networkService.request(resource)
```
- parameter resource: The resource you want to fetch.
- returns: a touple containing the parsed result and the HTTP response
- Throws: Custom Error provided by ResourceWithError
*/
@discardableResult
func request<Result, E: Error>(_ resource: ResourceWithError<Result, E>) async throws -> (Result, HTTPURLResponse) {
var task: NetworkTask?
let cancel = { task?.cancel() }
return try await withTaskCancellationHandler(operation: {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation({ coninuation in
task = request(resource: resource, onCompletionWithResponse: {
coninuation.resume(with: $0)
})
})
}, onCancel: {
cancel()
})
}
}