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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,25 @@ See [`example/nested_demo.cpp`](rclcpp_async/example/nested_demo.cpp) for a full
| `post(fn)` | `void` | Post a callback to the executor thread (thread-safe) |
| `node()` | `Node::SharedPtr` | Access the underlying node |

### Task

| Method | Returns | Description |
|---|---|---|
| `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) |
| `cancel()` | `void` | Request cancellation via `CancelledException` |

```cpp
auto task = ctx.create_task(run(ctx));

if (task) { // true -- valid coroutine
// ...
}
if (task.done()) {
// coroutine has finished
}
```

## License

Apache-2.0
6 changes: 6 additions & 0 deletions rclcpp_async/include/rclcpp_async/task.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ struct Task

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

explicit operator bool() const noexcept { return handle != nullptr; }
bool done() const noexcept { return handle && handle.done(); }

~Task()
{
if (handle) {
Expand Down Expand Up @@ -220,6 +223,9 @@ struct Task<void>

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

explicit operator bool() const noexcept { return handle != nullptr; }
bool done() const noexcept { return handle && handle.done(); }

~Task()
{
if (handle) {
Expand Down
35 changes: 35 additions & 0 deletions rclcpp_async/test/test_task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,38 @@ TEST(TaskT, AwaitLazyStillWorks)
ASSERT_TRUE(task.handle.done());
EXPECT_EQ(*task.handle.promise().value, 43);
}

TEST(TaskT, OperatorBoolAndDone)
{
auto task = returns_42();
EXPECT_TRUE(static_cast<bool>(task));
EXPECT_FALSE(task.done());

task.handle.resume();
EXPECT_TRUE(static_cast<bool>(task));
EXPECT_TRUE(task.done());

// After move, source becomes null
auto task2 = std::move(task);
EXPECT_FALSE(static_cast<bool>(task));
EXPECT_FALSE(task.done());
EXPECT_TRUE(static_cast<bool>(task2));
EXPECT_TRUE(task2.done());
}

TEST(TaskVoid, OperatorBoolAndDone)
{
auto task = does_nothing();
EXPECT_TRUE(static_cast<bool>(task));
EXPECT_FALSE(task.done());

task.handle.resume();
EXPECT_TRUE(static_cast<bool>(task));
EXPECT_TRUE(task.done());

auto task2 = std::move(task);
EXPECT_FALSE(static_cast<bool>(task));
EXPECT_FALSE(task.done());
EXPECT_TRUE(static_cast<bool>(task2));
EXPECT_TRUE(task2.done());
}