Skip to content

Commit 5638930

Browse files
authored
Better way to detect cancellation. (#3755)
1 parent d2c1bfb commit 5638930

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

Sources/ComposableArchitecture/Effect.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ extension Effect {
102102
} catch is CancellationError {
103103
return
104104
} catch {
105+
guard !Task.isCancelled
106+
else { return }
105107
guard let handler else {
106108
reportIssue(
107109
"""

Tests/ComposableArchitectureTests/EffectCancellationTests.swift

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,22 @@ final class EffectCancellationTests: BaseTCATestCase {
285285
}
286286
XCTAssertEqual(output, [1, 2])
287287
}
288+
289+
@available(iOS 15.0, *)
290+
func testCancellationWithoutThrowingCancellationError() async throws {
291+
let effect = Effect<Void>.run { send in
292+
let session = URLSession(configuration: .ephemeral)
293+
let request = URLRequest(url: URL(string: "http://ipv4.download.thinkbroadband.com/1GB.zip")!)
294+
let (data, response) = try await session.data(for: request, delegate: nil)
295+
_ = (data, response)
296+
}
297+
.cancellable(id: 1)
298+
Task {
299+
for await _ in effect.actions {}
300+
}
301+
try await Task.sleep(nanoseconds: 10_000_000)
302+
Task.cancel(id: 1)
303+
}
288304
}
289305

290306
#if DEBUG
@@ -350,15 +366,17 @@ final class EffectCancellationTests: BaseTCATestCase {
350366
.publisher {
351367
Just(idx)
352368
.delay(
353-
for: .milliseconds(Int.random(in: 1...100)), scheduler: queues.randomElement()!
369+
for: .milliseconds(Int.random(in: 1...100)),
370+
scheduler: queues.randomElement()!
354371
)
355372
}
356373
.cancellable(id: id),
357374

358375
.publisher {
359376
Empty()
360377
.delay(
361-
for: .milliseconds(Int.random(in: 1...100)), scheduler: queues.randomElement()!
378+
for: .milliseconds(Int.random(in: 1...100)),
379+
scheduler: queues.randomElement()!
362380
)
363381
.handleEvents(receiveCompletion: { _ in Task.cancel(id: id) })
364382
}

0 commit comments

Comments
 (0)