Skip to content

Commit 2988540

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 d22e84d commit 2988540

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
@@ -51,6 +51,8 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
5151
queue.append((key: key, channel: channel))
5252

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

@@ -158,11 +160,7 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
158160

159161
if cache[cacheKey] == nil {
160162
let channel = Channel<Value, Error>()
161-
162-
Task.detached {
163-
await channel.fulfill(value)
164-
}
165-
163+
await channel.fulfill(value)
166164
cache[cacheKey] = channel
167165
}
168166

0 commit comments

Comments
 (0)