chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.73k stars 1.2k forks source link

How to replace ASIO_CORO_YIELD with co_await and support the calling methods of both coroutines and callback #1354

Closed zhllxt closed 10 months ago

zhllxt commented 10 months ago

We can use the following code to compose some asynchronous operations:

struct wait_timer_op : public asio::coroutine
{
    asio::steady_timer& timer_;

    wait_timer_op(asio::steady_timer& timer) : timer_(timer) {}

    template <typename Self>
    void operator()(Self& self, asio::error_code ec = {})
    {
        ASIO_CORO_REENTER(*this)
        {
            ASIO_CORO_YIELD
                timer_.async_wait(std::move(self));

            self.complete(ec);
        }
    }
};

template <typename CompletionToken>
auto async_wait_timer(
    asio::steady_timer& timer, CompletionToken&& token)
{
    return asio::async_compose<CompletionToken, void(asio::error_code)>(
        wait_timer_op{ timer },
        token, timer);
}

then we can use it like this:

  1. coroutine
    co_await async_wait_timer(timer, asio::use_awaitable);
  2. callback
    async_wait_timer(timer, [](asio::error_code ec) {});

i want to know: how to modify struct wait_timer_op and replace ASIO_CORO_YIELD with c++ 20 coroutine, and supports multiple invocation methods such as coroutine and callback simultaneously?

klemens-morgenstern commented 10 months ago

Take a look at asio::experimental::co_composed.

zhllxt commented 10 months ago

Thank you. After testing, I found out that this is what I want.