smol-rs / futures-lite

Futures, streams, and async I/O combinators.
Apache License 2.0
439 stars 25 forks source link

Function to get the current waker in an async fn #8

Closed jjl closed 1 year ago

jjl commented 4 years ago

Not sure about the name, but I just found a use for this and it's incredibly small. Maybe you have a better idea for a name?

pub async fn waker() -> Waker {
    future::poll_fn(|c| Poll::Ready(c.waker().clone())).await
}
jjl commented 4 years ago

slightly more contentious bonus:

pub async fn delay() {
    let mut done = false;
    future::poll_fn(|_| {
        if done {
            Poll::Ready(())
        } else {
            done = true;
            Poll::Pending
        }
    }).await
}
ghost commented 4 years ago

I've wanted waker() before, more than once :) I think it's useful! The name sounds good to me. Some other ideas: get_waker(), current_waker(). Not sure if its possible, but perhaps it'd be worth changing the signature to return a &Waker rather than Waker.

Regarding delay(), I think that's same as futures_lite::future::yield_now().

jjl commented 4 years ago

AIUI, yield_now() reschedules the current future? Delay is for when you don't want to do that (because you're messing with wakers)

jjl commented 4 years ago

I went and looked, and yes, that's the essential difference - with delay, we don't wake ourselves.

jjl commented 4 years ago

These have now made it into futures-micro as 'waker' and 'sleep'. You might also like to steal PollState. Or you might find it offensive and decide not to :)

notgull commented 1 year ago

See this comment. I don't think we should add this; it's a bit niche.