Coder Social home page Coder Social logo

spencerjibz / async-event-emitter-rs Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 1.0 47 KB

Lightweight AsyncEventEmitter for rust

Home Page: https://docs.rs/async-event-emitter/0.1.1/async_event_emitter/

License: MIT License

Rust 100.00%
async async-callback async-rust event-emitter library tokio

async-event-emitter-rs's Introduction

async-event-emitter

Crates.io docs.rs CI codecov License: MIT

an Async implementation of the event-emitter-rs crate

Allows you to subscribe to events with callbacks and also fire those events. Events are in the form of (strings, value) and callbacks are in the form of closures that take in a value parameter;

Differences between this crate and event-emitter-rs

  • Emitted values should implement an extra trait (Debug) in addition to Serde's Serialize and Deserialize.
  • This is an async implementation, currently limited to tokio, but async-std will be added soon under a feature flag.
  • The listener methods (on and once) take a callback that returns a future instead of a merely a closure.
  • The emit methods executes each callback on each event by spawning a tokio task instead of a std::thread

Getting Started

    use async_event_emitter::AsyncEventEmitter;
    #[tokio::main]
    async fn main() {
        let mut event_emitter = AsyncEventEmitter::new();
        // This will print <"Hello world!"> whenever the <"Say Hello"> event is emitted
        event_emitter.on("Say Hello", |_: ()| async move { println!("Hello world!") });
        event_emitter.emit("Say Hello", ()).await.unwrap();
        // >> "Hello world!"
    }

Basic Usage

We can emit and listen to values of any type so long as they implement the Debug trait and serde's Serialize and Deserialize traits. A single EventEmitter instance can have listeners to values of multiple types.

    use async_event_emitter::AsyncEventEmitter as EventEmitter;
    use serde::{Deserialize, Serialize};

    #[tokio::main]
    async fn main() -> anyhow::Result<()> {
        let mut event_emitter = EventEmitter::new();
        event_emitter.on("Add three", |number: f64| async move {
            println!("{}", number + 3.0)
        });

        event_emitter.emit("Add three", 5.0_f64).await?;
        event_emitter.emit("Add three", 4.0_f64).await?;

        // >> "8.0"
        // >> "7.0"

        // Using a more advanced value type such as a struct by implementing the serde traits
        #[derive(Serialize, Deserialize, Debug)]
        struct Date {
            month: String,
            day: String,
        }

        event_emitter.on(
            "LOG_DATE",
            |_date: Date| async move { println!("{_date:?}") },
        );
        event_emitter
            .emit(
                "LOG_DATE",
                Date {
                    month: "January".to_string(),
                    day: "Tuesday".to_string(),
                },
            )
            .await?;
        event_emitter
            .emit(
                "LOG_DATE",
                Date {
                    month: "February".to_string(),
                    day: "Tuesday".to_string(),
                },
            )
            .await?;
        // >> "Month: January - Day: Tuesday"
        // >> "Month: January - Day: Tuesday"

        Ok(())
    }

Removing listeners is also easy

    use async_event_emitter::AsyncEventEmitter as EventEmitter;
    let mut event_emitter = EventEmitter::new();

    let listener_id = event_emitter.on("Hello", |_: ()| async { println!("Hello World") });
    match event_emitter.remove_listener(&listener_id) {
        Some(listener_id) => println!("Removed event listener! {listener_id}"),
        None => println!("No event listener of that id exists"),
    }

Creating a Global EventEmitter

You'll likely want to have a single EventEmitter instance that can be shared across files;

After all, one of the main points of using an EventEmitter is to avoid passing down a value through several nested functions/types and having a global subscription service.

        // global_event_emitter.rs
        use async_event_emitter::AsyncEventEmitter;
        use futures::lock::Mutex;
        use lazy_static::lazy_static;

        // Use lazy_static! because the size of EventEmitter is not known at compile time
        lazy_static! {
        // Export the emitter with `pub` keyword
        pub static ref EVENT_EMITTER: Mutex<AsyncEventEmitter> = Mutex::new(AsyncEventEmitter::new());
        }

        #[tokio::main]
        async fn main() -> anyhow::Result<()> {
            // We need to maintain a lock through the mutex so we can avoid data races
            EVENT_EMITTER
                .lock()
                .await
                .on("Hello", |_: ()| async { println!("hello there!") });
            EVENT_EMITTER.lock().await.emit("Hello", ()).await?;

            Ok(())
        }

        async fn random_function() {
            // When the <"Hello"> event is emitted in main.rs then print <"Random stuff!">
            EVENT_EMITTER
                .lock()
                .await
                .on("Hello", |_: ()| async { println!("Random stuff!") });
        }

License

MIT License (MIT), see LICENSE

async-event-emitter-rs's People

Contributors

github-actions[bot] avatar spencerjibz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

gabrielgrover

async-event-emitter-rs's Issues

add CI and tests

Add CI tests for our library, including clippy and docs tests

add CD workflow

  • Add a workflow that publishes a new release of our crate to crates.io.

  • This workflow should also update the version number in "cargo.toml" and create a branch for the updated version

format code examples

Currently, the code examples in the repo readme aren't well formatted as cargo fmt doesn't work for docs comment.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.