-
If I need a persistent connection like to a database or a web socket or something like that if I create it in main and then pass it to handlers will that work? Like this: async fn main() {
let conn = db::create_connection();
let mut request_receiver = bridge::get_request_receiver();
while let Some(request_unique) = request_receiver.recv().await {
tokio::spawn(async {
let response_unique = handle_request(&conn, request_unique).await;
respond_to_dart(response_unique);
});
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
temeddix
Dec 11, 2023
Replies: 1 comment 5 replies
-
Hi @milesegan , thank you for your participation! Your code might work, but I recommend using use std::cell::OnceCell;
let conn_cell = OnceCell::new();
async fn main() {
let conn = db::create_connection();
conn_cell.set(conn);
let mut request_receiver = bridge::get_request_receiver();
while let Some(request_unique) = request_receiver.recv().await {
tokio::spawn(async {
let response_unique = handle_request(request_unique).await;
respond_to_dart(response_unique);
});
}
}
async fn some_other_function() {
let conn = conn_cell.get().unwrap();
// Do something with `conn`
} (I haven't actually tested this code, but it should work) |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
milesegan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @milesegan , thank you for your participation!
Your code might work, but I recommend using
OnceCell
instead. If you useOnceCell
, yourconn
becomes a global variable that you can access from anywhere viacrate::conn_cell
.