Is State cloned for each request? #1911
-
Hi, I'm a little bit confused with clone and Arc when using I have the following AppState: use tokio::sync::mpsc;
#[derive(Clone)]
pub struct ActorHandle {
sender: mpsc::Sender<ActorMessage>,
}
impl ActorHandle {
pub async fn send_msg(&self, msg: ActorMessage) {
self.sender.send(msg).await;
}
}
#[derive(Clone)]
pub struct AppState {
pub actor_handle: ActorHandle,
} When I create my axum router I create a regular AppState without Arc: use tokio::sync::mpsc;
let (sender, receiver) = mpsc::channel(32);
let app_state = AppState {
actor_handle: ActorHandle { sender }
};
let router = Router::new()
.route("/foo", post(foo))
.with_state(app_state); Then I use it in the handler as a regular variable: pub async fn foo(State(state): State<AppState>) -> impl IntoResponse {
// msg creation omitted for brevity
state.actor_handle.send_msg(msg).await; // should I use state.clone() and then use the variable "actor_handle"?
} Is this legal? do I need to clone or add Arc type to my state if this is my use case? |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Apr 5, 2023
Replies: 1 comment 5 replies
-
Yes the state is cloned for each request. Otherwise you wouldn't be able to extract an owned state. |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
soasada
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes the state is cloned for each request. Otherwise you wouldn't be able to extract an owned state.