Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,7 @@ See [rclcpp_async/test/benchmark/README.md](rclcpp_async/test/benchmark/README.m
|---|---|---|
| `operator bool()` | `bool` | `true` if the task holds a valid coroutine (not moved-from) |
| `done()` | `bool` | `true` if the coroutine has completed (`false` for null tasks) |
| `result()` | `T&` | Get the result of a completed `Task<T>` (rethrows if exception) |
| `cancel()` | `void` | Request cancellation via `CancelledException` |

```cpp
Expand All @@ -638,7 +639,7 @@ if (task) { // true -- valid coroutine
// ...
}
if (task.done()) {
// coroutine has finished
auto & value = task.result(); // access the result without co_await
}
```

Expand Down
8 changes: 8 additions & 0 deletions rclcpp_async/include/rclcpp_async/task.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ struct Task
return std::move(*handle.promise().value);
}

T & result()
{
if (handle.promise().exception) {
std::rethrow_exception(handle.promise().exception);
}
return *handle.promise().value;
}

void cancel() { handle.promise().stop_source.request_stop(); }

explicit operator bool() const noexcept { return handle != nullptr; }
Expand Down
25 changes: 25 additions & 0 deletions rclcpp_async/test/test_task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,31 @@ TEST(TaskT, OperatorBoolAndDone)
EXPECT_TRUE(task2.done());
}

TEST(TaskT, ResultReturnsValue)
{
auto task = returns_42();
task.handle.resume();
ASSERT_TRUE(task.done());
EXPECT_EQ(task.result(), 42);
}

TEST(TaskT, ResultReturnsReference)
{
auto task = returns_42();
task.handle.resume();
ASSERT_TRUE(task.done());
task.result() = 99;
EXPECT_EQ(task.result(), 99);
}

TEST(TaskT, ResultRethrowsException)
{
auto task = throws_runtime_error();
task.handle.resume();
ASSERT_TRUE(task.done());
EXPECT_THROW(task.result(), std::runtime_error);
}

TEST(TaskVoid, OperatorBoolAndDone)
{
auto task = does_nothing();
Expand Down