Created
December 21, 2022 21:30
-
-
Save ankittlp/e117ceb27ceca6a59db8e5bb07a820e9 to your computer and use it in GitHub Desktop.
MultipleHeavyAsynchronousCallBackTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func multipleHeavyAsynchronousCallBackTask(start: Int, end: Int, completionHandler: @escaping ([Int]) -> Void) { | |
//1. Gets the array of numbers (A dummy heavy operation) | |
HeavyOperationApi.shared.heavyNumberArray(from: start, to: end) { numbers in | |
//2. Using the numbers array to fillter for Even number (A Dummy heavy operation) | |
HeavyOperationApi.shared.heavyFilterEvenNumberFrom(arrayOf: numbers) { evenNumbers in | |
// 3. Doing Random mapping of even numbers array (A Dummy Heavy operation) | |
HeavyOperationApi.shared.heavyRandomMapping(arrayOf: evenNumbers) { number in | |
return number + 10000000 | |
} completion: { transformedNumbrs in | |
completionHandler(transformedNumbrs) | |
} | |
} | |
} | |
} | |
enum HeavyOperationApiError: LocalizedError { | |
case reserveNumberError | |
} | |
class HeavyOperationApi { | |
private let sleepTime: UInt64 = 10 | |
static let shared = HeavyOperationApi() | |
private init() {} | |
func heavyNumberArray(from: Int, to: Int, completion: @escaping /*@Sendable*/ ([Int]) -> Void) { | |
DispatchQueue.global(qos: .userInitiated).async { | |
var number: [Int] = [] | |
for i in from...to { | |
number.append(i) | |
} | |
completion(number) | |
} | |
} | |
func heavyFilterEvenNumberFrom(arrayOf numbers: [Int], completion: @escaping /*@Sendable*/ ([Int]) -> Void ) { | |
DispatchQueue.global(qos: .userInitiated).async { | |
completion(numbers.filter { number in | |
number % 2 == 0 | |
}) | |
} | |
} | |
func heavyRandomMapping<T>(arrayOf numbers: [Int], transform: @escaping @Sendable (Int) -> T, completion: @escaping @Sendable ([T]) -> Void) { | |
DispatchQueue.global(qos: .userInitiated).async { | |
completion(numbers.map { number in | |
transform(number) | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment