Skip to content

Commit d48a93a

Browse files
fix: Changes detached Tasks to child tasks
This improves the cancellation behavior of the DataLoader fulfillment tasks in cases where only single keys are loaded It also removes data races associated with `prime` where the value may not be fully primed by the time the function succeeds.
1 parent d380f0d commit d48a93a

1 file changed

Lines changed: 4 additions & 6 deletions

File tree

Sources/AsyncDataLoader/DataLoader.swift

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
5252
queue.append((key: key, channel: channel))
5353

5454
if let executionPeriod = options.executionPeriod, !dispatchScheduled {
55+
// This task must be detached in order to fulfill potential other keys
56+
// even if the originally triggering key is cancelled.
5557
Task.detached {
5658
try await Task.sleep(nanoseconds: executionPeriod)
5759
try await self.execute()
@@ -60,7 +62,7 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
6062
dispatchScheduled = true
6163
}
6264
} else {
63-
Task.detached {
65+
Task {
6466
do {
6567
let results = try await self.batchLoadFunction([key])
6668

@@ -147,11 +149,7 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
147149

148150
if cache[cacheKey] == nil {
149151
let channel = Channel<Value, Error>()
150-
151-
Task.detached {
152-
await channel.fulfill(value)
153-
}
154-
152+
await channel.fulfill(value)
155153
cache[cacheKey] = channel
156154
}
157155

0 commit comments

Comments
 (0)