Skip to content

Commit

Permalink
style(TaskOperation): add separate error for retrieving result with…
Browse files Browse the repository at this point in the history
…out starting
  • Loading branch information
soumyamahunt committed Aug 23, 2022
1 parent 571419d commit 9a852d9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 9 additions & 1 deletion Sources/AsyncObjects/TaskOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
/// Will be success if provided operation completed successfully,
/// or failure returned with error.
public var result: Result<R, Error> {
get async { (await execTask?.result) ?? .failure(CancellationError()) }
get async { (await execTask?.result) ?? .failure(EarlyInvokeError()) }
}

/// Creates a new operation that executes the provided asynchronous task.
Expand Down Expand Up @@ -268,3 +268,11 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
try? await _withPromisedContinuation()
}
}

/// An error that indicates that operation result
/// requested without starting operation.
///
/// Error is thrown by ``TaskOperation/result``
/// if the operation hasn't been started yet with either
/// ``TaskOperation/start()`` or ``TaskOperation/signal()``.
public struct EarlyInvokeError: Error, Sendable {}
14 changes: 14 additions & 0 deletions Tests/AsyncObjectsTests/TaskOperationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,18 @@ class TaskOperationTests: XCTestCase {
await operation.wait()
}
}

func testNotStartedError() async throws {
let operation = TaskOperation { try await Self.sleep(seconds: 1) }
let result = await operation.result
switch result {
case .success: XCTFail("Unexpected operation result")
case .failure(let error):
XCTAssertTrue(type(of: error) == EarlyInvokeError.self)
print(
"[\(#function)] [\(type(of: error))] \(error.localizedDescription)"
)
XCTAssertFalse(error.localizedDescription.isEmpty)
}
}
}

0 comments on commit 9a852d9

Please sign in to comment.