How to use AppHandle in function that is in another runtime? #10784
-
I have a function that listens to file changes on device, if changes occur it sends event to frontend via
my simplified code: .setup(|app| {
let app_handle = Arc::new(Mutex::new(app.handle().clone()));
let app_handle_clone = app_handle.clone();
tauri::async_runtime::spawn(async move {
let app_handle = app_handle_clone.clone();
let (file_watcher_tx, file_watcher_rx) = mpsc::channel(32); // channel that messages what linked_path has been changed
// Initialize the file watcher
if let Err(e) = setup_file_watcher(app_handle.clone(), file_watcher_tx).await {
eprintln!("Error setting up file watcher: {}", e);
}
});
Ok(())
}) I want to note that Im using AppHandle directly and not a reference because if reference is passed, and |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If your implementation of #[cfg(target_os = "linux")]
pub fn run() {
use std::thread;
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.setup(|app| {
let app_handle = app.handle().clone();
thread::spawn(|| {
server::init(app_handle).unwrap();
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running the application");
} struct AppState {
tauri: AppHandle,
}
#[actix_web::main]
pub async fn init(tauri: AppHandle) -> Result<(), io::Error> {
let app_data = web::Data::new(AppState { tauri });
let http_server = HttpServer::new(move || {
App::new()
.app_data(app_data.clone())
.service(handlers::system::execute_command)
})
.bind(("0.0.0.0", 1111))
.expect("failed to bind address")
.run();
println!("Server started at http://0.0.0.0:1111");
http_server.await
} #[post("/system/{action}")]
async fn execute_command(
(action, payload, data): (Path<String>, Json<ExecuteCommandPayload>, Data<AppState>),
) -> HttpResponse {
let shell = data.tauri.shell();
// ...
|
Beta Was this translation helpful? Give feedback.
If your implementation of
setup_file_watcher
doesn't spawn more threads, you may not need Arc or even a Mutex. In my case I needed a way to access the app_handle in any actix-web handler, so I racked my brain for a few days to make it to work, as I had just started using tauri and rust. I tried with Box and Mutex at first, following this post, but it didn't work (compiled) for me. So after making some changes and later on, simplifying a little more, it worked with as little as this: