How would you refactor this code to use std's Mutex instead of Tokio's mutex
Edit: Changed image to show the function calling the alert message.
Hi, I am trying to replace all tokio::sync::Mutex with std::sync::Mutex. But this is kinda getting in the way. How would I refactor this to make it work okay with std's mutex?
Socket is a SplitSink for every connected websocket connection. This function is used to send them an alert message. This method is called from inside a tokio::task::spawn, which is listening for new messages
Send alert method with tokio Mutex-
pub async fn send_alert(socket: Socket, message: &str) {
socket
.lock()
.await
.send(Message::Text(
json!({
"type": "Alert",
"message":message.to_owned()
})
.to_string(),
))
.await
.unwrap();
}
tokio::task::spawn with tokio mutex. Causes issues when I switch over to the std::sync::Mutex \-
tokio::task::spawn(async move {
while let Some(request) = rx.recv().await {
match request.action {
WsActions::FriendRequestConfirmed(username) => {
AlertMessage::send_alert(
socket.clone(),
&format!("{} accepted your friend request", username),
)
.await;
}
_ => {
println!("Other action...");
}
}
}
// Causing issues 👇🏻 Says - socket is used across await keyword
// (which is not `Send`)
socket.lock().await.close().await.unwrap();
});
For old.reddit users -