-
Notifications
You must be signed in to change notification settings - Fork 76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to use shared variable in async callback #425
Comments
This can be fixed by an additional clone: let tx_clone = tx.clone();
let callback = |payload: Payload, socket: Client| {
let tx_clone = tx_clone.clone();
async move {
tx_clone.send("...".to_string());
}.boxed()
};
let callback2 = |payload: Payload, socket: Client| {
let tx = tx.clone();
async move {
tx.send("...".to_string());
}.boxed()
}; this is untested but how I recall fixing this. It's not by any means ideal but #363 is likely related |
Thanks! I figured this out. But what I ended up doing is use Here is how I did it. #[derive(Debug)]
pub struct EventMessage {
pub event: String,
pub payload: Payload,
}
let (done_tx, mut done_rx) = tokio::sync::mpsc::channel::<()>(1);
let (evt_tx, mut evt_rx) = tokio::sync::mpsc::channel::<EventMessage>(1);
let socket = ClientBuilder::new(SERVER_URL)
.on(Event::Connect, |_, _| async move {}.boxed())
.on_any(move |evt, payload, _| {
let evt_tx = evt_tx.clone();
async move {
evt_tx
.send(EventMessage {
event: evt.to_string(),
payload,
})
.await
.unwrap();
}
.boxed()
})
.on(Event::Error, |err, _: Client| {
async move {
eprintln!("Error: {:#?}", err);
}
.boxed()
})
.connect()
.await
.expect("Connection failed");
loop {
tokio::select! {
_ = done_rx.recv() => {
break;
}
Some(evt) = evt_rx.recv() => {
// Handle event received from evt_rx
match evt.event.as_str() {
"evt1" => {...}
"evt2" => {...}
}
}
_ = tokio::signal::ctrl_c() => {
break;
}
};
} |
@1c3t3a |
about this, I'm also thinking about another thing, how to share a "status data" between different callback function? |
Using the regular version works
but if I switch to use the async version
Using the Async version I always get error:
Couldn't figure out how to fix this. Also could not find examples on this.
All examples I could find are the simplest where callback doesn't need to access external variables.
The text was updated successfully, but these errors were encountered: