How can I get waker from the current async fn

Say, the code

async fn a() {
    let ctx = ?//
    let waker = ctx.waker().clone();
}


a.await;

how can I get Context in a? I do can get it using:

async fn a() {
    struct waker_struct()
    impl Future for waker_struct() {
          fn poll(_, ctx: Context<'_>) -> Poll<waker> {
                 ctx.waker().clone()
         }
    }
    let waker = waker_future.await
}

a.await;

But it looks strange

What do you need the waker for?

Implementing a Future and having it return the Waker is the only way, though it can be done easier than what you posted using poll_fn.

use futures::future::poll_fn;
use std::task::{Poll, Waker};

async fn get_waker() -> Waker {
    poll_fn(|cx| Poll::Ready(cx.waker().clone())).await
}

Of course, you should be aware that the waker of an async fn can change from one poll to another, so you risk waking the wrong waker when doing this.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.