Skip to content

Commit f0ac8f9

Browse files
committed
add docs for new task methods
1 parent d75d283 commit f0ac8f9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tutorials/tasks.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,3 +259,45 @@ $execute {
259259
```
260260

261261
Note that if your code needs to interact with the Cocos2d UI **at all**, then you should probably be using an `EventListener` in some node or a manager class instead.
262+
263+
## Chaining tasks
264+
265+
You can chain tasks by using `Task::chain`. This allows you to take the result of a task once it finished and run another task right after, based on that return value. \
266+
Progress updates are only sent from the last Task in the chain, for simplicity
267+
268+
```cpp
269+
Task<std::string> newTask =
270+
startCalculation()
271+
.chain([](uint64_t value) -> Task<std::string> {
272+
// do something expensive with the value idk
273+
// this is a bad example
274+
return Task<std::string>::immediate(fmt::format("{}", value));
275+
});
276+
```
277+
278+
## Coroutines
279+
280+
Tasks can be used in [C++20 coroutine](https://en.cppreference.com/w/cpp/language/coroutines) functions, easily allowing for multiple asynchronous calls to happen within the same code. Note that this may have a little performance overhead compared to regular Task code.
281+
282+
```cpp
283+
Task<int> someTask() {
284+
auto response = co_await web::WebRequest().get("https://example.com");
285+
co_return response.code();
286+
}
287+
```
288+
289+
There are a few specific things you should be aware of when using this syntax:
290+
* The body of the coroutine is ran in whatever thread it got called in
291+
* If the task the coroutine is waiting on is cancelled, the whole coroutine is cancelled
292+
* If the task returned by the coroutine is cancelled, any pending task that is running is cancelled
293+
294+
You can also send progress values using `co_yield`
295+
296+
```cpp
297+
Task<std::string, int> someTask() {
298+
for (int i = 0; i < 10; i++) {
299+
co_yield i;
300+
}
301+
co_return "done!";
302+
}
303+
```

0 commit comments

Comments
 (0)