Function tauri::async_runtime::spawn
source · pub fn spawn<F>(task: F) -> JoinHandle<F::Output> ⓘwhere
F: Future + Send + 'static,
F::Output: Send + 'static,
Expand description
Spawns a future onto the runtime.
Examples found in repository?
src/app.rs (line 902)
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
fn run_updater_dialog(&self) {
let handle = self.handle();
crate::async_runtime::spawn(async move { updater::check_update_with_dialog(handle).await });
}
fn run_updater(&self) {
let handle = self.handle();
let handle_ = handle.clone();
let updater_config = self.manager.config().tauri.updater.clone();
// check if updater is active or not
if updater_config.active {
if updater_config.dialog {
#[cfg(not(target_os = "linux"))]
let updater_enabled = true;
#[cfg(target_os = "linux")]
let updater_enabled = cfg!(dev) || self.state::<Env>().appimage.is_some();
if updater_enabled {
// if updater dialog is enabled spawn a new task
self.run_updater_dialog();
// When dialog is enabled, if user want to recheck
// if an update is available after first start
// invoke the Event `tauri://update` from JS or rust side.
handle.listen_global(updater::EVENT_CHECK_UPDATE, move |_msg| {
let handle = handle_.clone();
// re-spawn task inside tokyo to launch the download
// we don't need to emit anything as everything is handled
// by the process (user is asked to restart at the end)
// and it's handled by the updater
crate::async_runtime::spawn(
async move { updater::check_update_with_dialog(handle).await },
);
});
}
} else {
// we only listen for `tauri://update`
// once we receive the call, we check if an update is available or not
// if there is a new update we emit `tauri://update-available` with details
// this is the user responsibilities to display dialog and ask if user want to install
// to install the update you need to invoke the Event `tauri://update-install`
updater::listener(handle);
}
}
}
More examples
src/hooks.rs (lines 185-187)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
pub fn respond_async<T, F>(self, task: F)
where
T: Serialize,
F: Future<Output = Result<T, InvokeError>> + Send + 'static,
{
crate::async_runtime::spawn(async move {
Self::return_task(self.window, task, self.callback, self.error).await;
});
}
/// Reply to the invoke promise with an async task which is already serialized.
pub fn respond_async_serialized<F>(self, task: F)
where
F: Future<Output = Result<JsonValue, InvokeError>> + Send + 'static,
{
crate::async_runtime::spawn(async move {
let response = match task.await {
Ok(ok) => InvokeResponse::Ok(ok),
Err(err) => InvokeResponse::Err(err),
};
Self::return_result(self.window, response, self.callback, self.error)
});
}
src/api/notification.rs (lines 132-134)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
pub fn show(self) -> crate::api::Result<()> {
let mut notification = notify_rust::Notification::new();
if let Some(body) = self.body {
notification.body(&body);
}
if let Some(title) = self.title {
notification.summary(&title);
}
if let Some(icon) = self.icon {
notification.icon(&icon);
} else {
notification.auto_icon();
}
#[cfg(windows)]
{
let exe = tauri_utils::platform::current_exe()?;
let exe_dir = exe.parent().expect("failed to get exe directory");
let curr_dir = exe_dir.display().to_string();
// set the notification's System.AppUserModel.ID only when running the installed app
if !(curr_dir.ends_with(format!("{S}target{S}debug", S = MAIN_SEPARATOR).as_str())
|| curr_dir.ends_with(format!("{S}target{S}release", S = MAIN_SEPARATOR).as_str()))
{
notification.app_id(&self.identifier);
}
}
#[cfg(target_os = "macos")]
{
let _ = notify_rust::set_application(if cfg!(feature = "custom-protocol") {
&self.identifier
} else {
"com.apple.Terminal"
});
}
crate::async_runtime::spawn(async move {
let _ = notification.show();
});
Ok(())
}
src/updater/mod.rs (lines 332-334)
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
pub async fn check(self) -> Result<UpdateResponse<R>> {
let handle = self.inner.app.clone();
let events = self.events;
// check updates
match self.inner.build().await {
Ok(update) => {
if events {
// send notification if we need to update
if update.should_update {
let body = update.body.clone().unwrap_or_else(|| String::from(""));
// Emit `tauri://update-available`
let _ = handle.emit_all(
EVENT_UPDATE_AVAILABLE,
UpdateManifest {
body: body.clone(),
date: update.date.map(|d| d.to_string()),
version: update.version.clone(),
},
);
let _ = handle.create_proxy().send_event(EventLoopMessage::Updater(
UpdaterEvent::UpdateAvailable {
body,
date: update.date,
version: update.version.clone(),
},
));
// Listen for `tauri://update-install`
let update_ = update.clone();
handle.once_global(EVENT_INSTALL_UPDATE, move |_msg| {
crate::async_runtime::spawn(async move {
let _ = download_and_install(update_).await;
});
});
} else {
send_status_update(&handle, UpdaterEvent::AlreadyUpToDate);
}
}
Ok(UpdateResponse { update })
}
Err(e) => {
if self.events {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
Err(e)
}
}
}
}
/// The response of an updater check.
pub struct UpdateResponse<R: Runtime> {
update: core::Update<R>,
}
impl<R: Runtime> Clone for UpdateResponse<R> {
fn clone(&self) -> Self {
Self {
update: self.update.clone(),
}
}
}
impl<R: Runtime> UpdateResponse<R> {
/// Whether the updater found a newer release or not.
pub fn is_update_available(&self) -> bool {
self.update.should_update
}
/// The current version of the application as read by the updater.
pub fn current_version(&self) -> &Version {
&self.update.current_version
}
/// The latest version of the application found by the updater.
pub fn latest_version(&self) -> &str {
&self.update.version
}
/// The update date.
pub fn date(&self) -> Option<&OffsetDateTime> {
self.update.date.as_ref()
}
/// The update description.
pub fn body(&self) -> Option<&String> {
self.update.body.as_ref()
}
/// Downloads and installs the update.
pub async fn download_and_install(self) -> Result<()> {
download_and_install(self.update).await
}
}
/// Check if there is any new update with builtin dialog.
pub(crate) async fn check_update_with_dialog<R: Runtime>(handle: AppHandle<R>) {
let updater_config = handle.config().tauri.updater.clone();
let package_info = handle.package_info().clone();
if let Some(endpoints) = updater_config.endpoints.clone() {
let endpoints = endpoints
.iter()
.map(|e| e.to_string())
.collect::<Vec<String>>();
let mut builder = self::core::builder(handle.clone())
.urls(&endpoints[..])
.current_version(package_info.version);
if let Some(target) = &handle.updater_settings.target {
builder = builder.target(target);
}
// check updates
match builder.build().await {
Ok(updater) => {
let pubkey = updater_config.pubkey.clone();
// if dialog enabled only
if updater.should_update && updater_config.dialog {
let body = updater.body.clone().unwrap_or_else(|| String::from(""));
let dialog =
prompt_for_install(&updater.clone(), &package_info.name, &body.clone(), pubkey).await;
if let Err(e) = dialog {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
Err(e) => {
send_status_update(&handle, UpdaterEvent::Error(e.to_string()));
}
}
}
}
/// Updater listener
/// This function should be run on the main thread once.
pub(crate) fn listener<R: Runtime>(handle: AppHandle<R>) {
// Wait to receive the event `"tauri://update"`
let handle_ = handle.clone();
handle.listen_global(EVENT_CHECK_UPDATE, move |_msg| {
let handle_ = handle_.clone();
crate::async_runtime::spawn(async move {
let _ = builder(handle_.clone()).check().await;
});
});
}
src/endpoints/shell.rs (lines 165-175)
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn execute<R: Runtime>(
context: InvokeContext<R>,
program: String,
args: ExecuteArgs,
on_event_fn: CallbackFn,
options: CommandOptions,
) -> super::Result<ChildId> {
let mut command = if options.sidecar {
#[cfg(not(shell_sidecar))]
return Err(crate::Error::ApiNotAllowlisted("shell > sidecar".to_string()).into_anyhow());
#[cfg(shell_sidecar)]
{
let program = PathBuf::from(program);
let program_as_string = program.display().to_string();
let program_no_ext_as_string = program.with_extension("").display().to_string();
let configured_sidecar = context
.config
.tauri
.bundle
.external_bin
.as_ref()
.map(|bins| {
bins
.iter()
.find(|b| b == &&program_as_string || b == &&program_no_ext_as_string)
})
.unwrap_or_default();
if let Some(sidecar) = configured_sidecar {
context
.window
.state::<Scopes>()
.shell
.prepare_sidecar(&program.to_string_lossy(), sidecar, args)
.map_err(crate::error::into_anyhow)?
} else {
return Err(crate::Error::SidecarNotAllowed(program).into_anyhow());
}
}
} else {
#[cfg(not(shell_execute))]
return Err(crate::Error::ApiNotAllowlisted("shell > execute".to_string()).into_anyhow());
#[cfg(shell_execute)]
match context
.window
.state::<Scopes>()
.shell
.prepare(&program, args)
{
Ok(cmd) => cmd,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("{}", e);
return Err(crate::Error::ProgramNotAllowed(PathBuf::from(program)).into_anyhow());
}
}
};
#[cfg(any(shell_execute, shell_sidecar))]
{
if let Some(cwd) = options.cwd {
command = command.current_dir(cwd);
}
if let Some(env) = options.env {
command = command.envs(env);
} else {
command = command.env_clear();
}
if let Some(encoding) = options.encoding {
if let Some(encoding) = crate::api::process::Encoding::for_label(encoding.as_bytes()) {
command = command.encoding(encoding);
} else {
return Err(anyhow::anyhow!(format!("unknown encoding {}", encoding)));
}
}
let (mut rx, child) = command.spawn()?;
let pid = child.pid();
command_child_store().lock().unwrap().insert(pid, child);
crate::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
if matches!(event, crate::api::process::CommandEvent::Terminated(_)) {
command_child_store().lock().unwrap().remove(&pid);
}
let js = crate::api::ipc::format_callback(on_event_fn, &event)
.expect("unable to serialize CommandEvent");
let _ = context.window.eval(js.as_str());
}
});
Ok(pid)
}
}