1c3t3a / rust-socketio

An implementation of a socket.io client written in the Rust programming language.
MIT License
408 stars 74 forks source link

Introduce Custom shared data structure #427

Open kitgxrl opened 5 months ago

kitgxrl commented 5 months ago

This idea was gotten from serenity-rs/serenity, while their implementation is much more nuanced I believe this can be simplified fairly heavily for most use cases.

The idea is to have some data structure that is shared amongst events, possibly accessed via socket.data() or something similar. This can indirectly solve #363 and #425

Some example code may be as such, taking example of #363:

struct MyData {
    tx: Sender<String>
}

fn main() {
    let (tx, rx) = mpsc::channel::<String>():

    let my_data = Arc::new(MyData {
        tx
    });

    let callback1 = |payload: Payload, socket: RawClient| {
        let data: Arc<MyData> = socket.data();

        data.tx.send("...".to_string());
    };

    let callback2 = |payload: Payload, socket: RawClient| {
        let data: Arc<MyData> = socket.data();

        data.tx.send("...".to_string());
    };

    let socket = ClientBuilder::new("...")
        .on("event1", callback1)
        .on("event2", callback2)
        .data(my_data)
        .connect()
        .expect("Connection failed");
}

I am absolutely willing to work on this, it is exam week at my college so it might be a week or two before I can get around to it but this implementation would greatly help in cases where shared data is absolutely required.