- Warning
- D++ Coroutines are a very new feature and are currently only supported by D++ on g++ 13, clang/LLVM 14, and MSVC 19.37 or above. Additionally, D++ must be built with the CMake option DPP_CORO, and your program must both define the macro DPP_CORO and use C++20 or above. The feature is experimental and may have bugs or even crashes, please report any to GitHub Issues or to our Discord Server.
In the last example we've explored how to await events using coroutines, we ran into the problem of the coroutine waiting forever if the button was never clicked. Wouldn't it be nice if we could add an "or" to our algorithm, for example wait for the button to be clicked or for a timer to expire? I'm glad you asked! D++ offers when_any which allows exactly that. It is a templated class that can take any number of awaitable objects and can be co_await
-ed itself, will resume when the first awaitable completes and return a result object that allows to retrieve which awaitable completed as well as its result, in a similar way as std::variant.
#include <dpp/dpp.h>
int main() {
dpp::message m{"Test"};
std::string id{event.command.id.str()};
)
);
event.from->creator->on_button_click.when([&id](const dpp::button_click_t &b) {
return b.custom_id == id;
}),
event.from->creator->co_sleep(5)
};
if (result.index() == 0) {
event.edit_original_response(
dpp::message{
"You clicked the button with the id " + click_event.
custom_id});
} else {
event.edit_original_response(
dpp::message{
"I haven't got all day!"});
}
}
});
if (dpp::run_once<struct register_bot_commands>()) {
bot.global_command_create(command);
}
});
return 0;
}
Any awaitable can be used with when_any, even dpp::task, dpp::coroutine, dpp::async. When the when_any object is destroyed, any of its awaitables with a cancel() method (for example dpp::task) will have it called. With this you can easily make commands that ask for input in several steps, or maybe a timed text game, the possibilities are endless! Note that if the first awaitable completes with an exception, result.get will throw it.
- Note
- when_any will try to construct awaitable objects from the parameter you pass it, which it will own. In practice this means you can only pass it temporary objects (rvalues) as most of the coroutine-related objects in D++ are move-only.