From ef41dff2c7fb6a02d6cd212ab5f0047c5e3fa775 Mon Sep 17 00:00:00 2001 From: dajiaohuang Date: Sun, 4 Oct 2026 10:09:59 +0800 Subject: [PATCH] Fix cancellation of suspended async sequence --- KMPNativeCoroutinesAsync/AsyncSequence.swift | 2 +- .../AsyncSequenceTests.swift | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/KMPNativeCoroutinesAsync/AsyncSequence.swift b/KMPNativeCoroutinesAsync/AsyncSequence.swift index d584287a..37aece29 100644 --- a/KMPNativeCoroutinesAsync/AsyncSequence.swift +++ b/KMPNativeCoroutinesAsync/AsyncSequence.swift @@ -65,7 +65,7 @@ public struct NativeFlowAsyncSequence: AsyncSequen defer { self.semaphore.signal() } self.cancellationError = cancellationError if let continuation = self.continuation { - continuation.resume(returning: nil) + continuation.resume(throwing: CancellationError()) self.continuation = nil } self.nativeCancellable = nil diff --git a/KMPNativeCoroutinesAsyncTests/AsyncSequenceTests.swift b/KMPNativeCoroutinesAsyncTests/AsyncSequenceTests.swift index 320d3f43..73a6cf88 100644 --- a/KMPNativeCoroutinesAsyncTests/AsyncSequenceTests.swift +++ b/KMPNativeCoroutinesAsyncTests/AsyncSequenceTests.swift @@ -34,6 +34,35 @@ class AsyncSequenceTests: XCTestCase { } XCTAssertTrue(error is CancellationError, "Error should be a CancellationError") } + + @MainActor + func testCancellationWhileNextIsSuspendedThrowsCancellationError() async { + let nextRequested = expectation(description: "The async iterator requested its first value") + var cancelCount = 0 + let nativeFlow: NativeFlow = { _, _, cancelCallback in + nextRequested.fulfill() + return { + cancelCount += 1 + cancelCallback(NSError(domain: "Ignored", code: 0), ()) + } + } + let handle = Task { + for try await _ in asyncSequence(for: nativeFlow) { } + } + + // The task inherits MainActor. After the expectation is fulfilled it continues + // synchronously into next() and suspends before this test resumes on MainActor. + await fulfillment(of: [nextRequested], timeout: 1) + handle.cancel() + + let result = await handle.result + XCTAssertEqual(cancelCount, 1, "Cancellable should be invoked once") + guard case let .failure(error) = result else { + XCTFail("Task should fail with an error") + return + } + XCTAssertTrue(error is CancellationError, "Error should be a CancellationError") + } func testCompletionWithCorrectValues() async { let values = [TestValue(), TestValue(), TestValue(), TestValue(), TestValue()]