#events #blocking #wake #park #condvar #reduce-boilerplate #envcount

no-std event-listener-strategy

Block or poll on event_listener easily

8 releases (4 breaking)

0.5.3 Nov 30, 2024
0.5.2 Apr 27, 2024
0.5.1 Mar 30, 2024
0.5.0 Feb 7, 2024
0.1.0 Sep 11, 2023

#872 in Asynchronous

Download history 861959/week @ 2024-08-23 830372/week @ 2024-08-30 893440/week @ 2024-09-06 828095/week @ 2024-09-13 955433/week @ 2024-09-20 909278/week @ 2024-09-27 1006872/week @ 2024-10-04 960546/week @ 2024-10-11 1025567/week @ 2024-10-18 1073746/week @ 2024-10-25 1003723/week @ 2024-11-01 1043926/week @ 2024-11-08 1055736/week @ 2024-11-15 916640/week @ 2024-11-22 935058/week @ 2024-11-29 951596/week @ 2024-12-06

4,072,174 downloads per month
Used in 5,533 crates (8 directly)

Apache-2.0 OR MIT

22KB
302 lines

event-listener-strategy

Build License Cargo Documentation

A strategy for using the event-listener crate in both blocking and non-blocking contexts.

One of the stand-out features of the event-listener crate is the ability to use it in both asynchronous and synchronous contexts. However, sometimes using it like this causes a lot of boilerplate to be duplicated. This crate aims to reduce that boilerplate by providing an EventListenerFuture trait that implements both blocking and non-blocking functionality.

Examples

use event_listener::{Event, EventListener};
use event_listener_strategy::{EventListenerFuture, FutureWrapper, Strategy};

use std::pin::Pin;
use std::task::Poll;
use std::thread;
use std::sync::Arc;

// A future that waits three seconds for an event to be fired.
fn wait_three_seconds() -> WaitThreeSeconds {
    let event = Event::new();
    let listener = event.listen();

    thread::spawn(move || {
        thread::sleep(std::time::Duration::from_secs(3));
        event.notify(1);
    });

    WaitThreeSeconds { listener }
}

struct WaitThreeSeconds {
    listener: Pin<Box<EventListener>>,
}

impl EventListenerFuture for WaitThreeSeconds {
    type Output = ();

    fn poll_with_strategy<'a, S: Strategy<'a>>(
        mut self: Pin<&'a mut Self>,
        strategy: &mut S,
        context: &mut S::Context,
    ) -> Poll<Self::Output> {
        strategy.poll(self.listener.as_mut(), context)
    }
}

// Use the future in a blocking context.
let future = wait_three_seconds();
future.wait();

// Use the future in a non-blocking context.
futures_lite::future::block_on(async {
    let future = FutureWrapper::new(wait_three_seconds());
    future.await;
});

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.3–24MB
~336K SLoC