I'm trying to create a background tasks in my BE code that calls an async function in a loop and emits the returned value as an even to the FE. The async function depends on a string that's part of the app's State and I'm struggling to pass the string into the async task without running into thread-safety errors. Here's a MWE:
#[derive(Serialize, Clone)]
struct DeploymentMonitor {
values: String,
}
impl DeploymentMonitor {
async fn get(tag: &str) -> Result<Self, Box<dyn Error>> {
Ok(Self { values: tag.into() })
}
}
#[derive(Default)]
struct AppSettings {
deployment_monitor_tag: Arc<Mutex<String>>,
}
#[tauri::command]
fn set_deployment_monitor_tag(tag: &str, settings: State<AppSettings>) {
dbg!(&tag);
let mut current_tag = settings.deployment_monitor_tag.lock().unwrap();
*current_tag = tag.to_string();
}
#[tauri::command]
fn setup_update_loop(window: Window, settings: State<AppSettings>) {
let tag = settings.deployment_monitor_tag.clone();
tauri::async_runtime::spawn(async move {
loop {
if let Ok(deployment_monitor) = DeploymentMonitor::get(&*tag.lock().unwrap()).await {
window.emit("update", deployment_monitor);
}
// TODO: sleep for 1 second
}
});
}
fn main() {
tauri::Builder::default()
.manage(AppSettings::default())
.invoke_handler(tauri::generate_handler![set_deployment_monitor_tag])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
The error I get is that the future in the async block cannot be send between threads because the tag is not Send. How can I fix this error?