1 unstable release

0.1.0 Jul 26, 2021

#1661 in Asynchronous

Download history 2343/week @ 2024-07-24 1753/week @ 2024-07-31 3090/week @ 2024-08-07 1938/week @ 2024-08-14 3046/week @ 2024-08-21 3148/week @ 2024-08-28 4761/week @ 2024-09-04 4880/week @ 2024-09-11 4258/week @ 2024-09-18 4712/week @ 2024-09-25 5215/week @ 2024-10-02 4260/week @ 2024-10-09 5610/week @ 2024-10-16 4766/week @ 2024-10-23 6122/week @ 2024-10-30 4062/week @ 2024-11-06

21,531 downloads per month
Used in async-quic

MIT/Apache

7KB

A waker that does nothing when it is woken. Useful for "now or never" type scenarioes where a future is unlikely to be polled more than once, or for "spinning" executors.

Example

A very inefficient implementation of the block_on function that polls the future over and over.

use core::{future::Future, hint::spin_loop, task::{Context, Poll}};
use futures_lite::future::poll_fn;
use noop_waker::noop_waker;

fn block_on<R>(f: impl Future<Output = R>) -> R {
    // pin the future to the stack
    futures_lite::pin!(f);

    // create the context
    let waker = noop_waker();
    let mut ctx = Context::from_waker(&waker);

    // poll future in a loop
    loop {
        match f.as_mut().poll(&mut ctx) {
            Poll::Ready(o) => return o,
            Poll::Pending => spin_loop(),
        }
    }
}

// this future returns pending 5 times before returning ready

let mut counter = 0;
let my_future = poll_fn(|ctx| {
    if counter < 5 {
        counter += 1;
        ctx.waker().wake_by_ref();
        Poll::Pending
    } else {
        Poll::Ready(7)
    }
});

assert_eq!(block_on(my_future), 7);

No runtime deps