Skip to content

Commit 4c197ff

Browse files
authored
Rewrite Dictionary flatten (#83)
1 parent 7aa6430 commit 4c197ff

File tree

1 file changed

+7
-26
lines changed

1 file changed

+7
-26
lines changed

Sources/GraphQL/Utilities/NIO+Extensions.swift

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,34 +28,14 @@ extension Collection {
2828

2929
extension Dictionary where Value : FutureType {
3030
func flatten(on eventLoopGroup: EventLoopGroup) -> Future<[Key: Value.Expectation]> {
31-
let queue = DispatchQueue(label: "org.graphQL.elementQueue")
32-
var elements: [Key: Value.Expectation] = [:]
33-
34-
guard self.count > 0 else {
35-
return eventLoopGroup.next().makeSucceededFuture(elements)
31+
// create array of futures with (key,value) tuple
32+
let futures: [Future<(Key, Value.Expectation)>] = self.map { element in
33+
element.value.map(file: #file, line: #line) { (key: element.key, value: $0) }
3634
}
37-
38-
let promise: EventLoopPromise<[Key: Value.Expectation]> = eventLoopGroup.next().makePromise()
39-
elements.reserveCapacity(self.count)
40-
41-
for (key, value) in self {
42-
value.whenSuccess { expectation in
43-
// Control access to elements to avoid thread conflicts
44-
queue.async {
45-
elements[key] = expectation
46-
47-
if elements.count == self.count {
48-
promise.succeed(elements)
49-
}
50-
}
51-
}
52-
53-
value.whenFailure { error in
54-
promise.fail(error)
55-
}
35+
// when all futures have succeeded convert tuple array back to dictionary
36+
return EventLoopFuture.whenAllSucceed(futures, on: eventLoopGroup.next()).map {
37+
.init(uniqueKeysWithValues: $0)
5638
}
57-
58-
return promise.futureResult
5939
}
6040
}
6141
extension Future {
@@ -86,6 +66,7 @@ public protocol FutureType {
8666
associatedtype Expectation
8767
func whenSuccess(_ callback: @escaping (Expectation) -> Void)
8868
func whenFailure(_ callback: @escaping (Error) -> Void)
69+
func map<NewValue>(file: StaticString, line: UInt, _ callback: @escaping (Expectation) -> (NewValue)) -> EventLoopFuture<NewValue>
8970
}
9071

9172
extension Future : FutureType {

0 commit comments

Comments
 (0)