diff --git a/src/lib.rs b/src/lib.rs index b4fd668..16b1f2b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -use std::pin::Pin; +use std::{pin::Pin, sync::Arc}; use serde::{Deserialize, Serialize}; @@ -9,7 +9,7 @@ pub mod ws; pub type Result = std::result::Result; pub type BoxFuture<'a, T = Option<(bool, serde_json::Value)>> = Pin + Send + 'a>>; -pub type MethodHandler = Box BoxFuture<'static> + Send + Sync>; +pub type MethodHandler = Arc BoxFuture<'static> + Send + Sync>; pub trait Method { const NAME: &'static str; diff --git a/src/session.rs b/src/session.rs index 1dd6e96..2443a85 100644 --- a/src/session.rs +++ b/src/session.rs @@ -87,7 +87,12 @@ impl Session { match msg { Message::Request { id, method, data } => { - if let Some(m) = s.methods.lock().await.get(&method) { + let handler = { + let methods = s.methods.lock().await; + methods.get(&method).cloned() + }; + + if let Some(m) = handler { if let Some((err, res)) = (m)(id, data).await { if err { s.respond_error(id, res) @@ -157,7 +162,7 @@ impl Session { self.methods.lock().await.insert( M::NAME.to_string(), - Box::new(move |id, value| { + Arc::new(move |id, value| { let handler = Arc::clone(&handler); Box::pin(async move {