Skip to content

Commit 7c2eb31

Browse files
feat: add PluginHandle::run_mobile_plugin_async (#13895)
* add async * chore: fmt * feat: add run_mobile_plugin_async * changes * chore: fix misplaced `}` * chore: fix minor pattern matching error * fix: copy the response handling directly from run_mobile_plugin * fix android build * Fix clippy lint * lint --------- Co-authored-by: Lucas Nogueira <[email protected]>
1 parent 737364b commit 7c2eb31

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri": minor:feat
3+
---
4+
5+
Introduces `PluginHandle::run_mobile_plugin_async` as an async alternative to `run_mobile_plugin`

crates/tauri/src/plugin/mobile.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ use crate::{
1313

1414
#[cfg(mobile)]
1515
use std::sync::atomic::{AtomicI32, Ordering};
16+
#[cfg(mobile)]
17+
use tokio::sync::oneshot;
1618

1719
use serde::{de::DeserializeOwned, Serialize};
1820

@@ -279,6 +281,38 @@ impl<R: Runtime, C: DeserializeOwned> PluginApi<R, C> {
279281
}
280282

281283
impl<R: Runtime> PluginHandle<R> {
284+
/// Executes the given mobile command.
285+
/// This is an async optimized variant of run_mobile_plugin
286+
pub async fn run_mobile_plugin_async<T: DeserializeOwned>(
287+
&self,
288+
command: impl AsRef<str>,
289+
payload: impl Serialize,
290+
) -> Result<T, PluginInvokeError> {
291+
let (tx, rx) = oneshot::channel();
292+
// the closure is an FnOnce but on Android we need to clone it (error handling)
293+
let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx)));
294+
run_command(
295+
self.name,
296+
&self.handle,
297+
command,
298+
serde_json::to_value(payload).map_err(PluginInvokeError::CannotSerializePayload)?,
299+
move |response| {
300+
tx.lock().unwrap().take().unwrap().send(response).unwrap();
301+
},
302+
)?;
303+
304+
let response = rx.await.unwrap();
305+
306+
match response {
307+
Ok(r) => serde_json::from_value(r).map_err(PluginInvokeError::CannotDeserializeResponse),
308+
Err(r) => Err(
309+
serde_json::from_value::<ErrorResponse>(r)
310+
.map(Into::into)
311+
.map_err(PluginInvokeError::CannotDeserializeResponse)?,
312+
),
313+
}
314+
}
315+
282316
/// Executes the given mobile command.
283317
pub fn run_mobile_plugin<T: DeserializeOwned>(
284318
&self,

0 commit comments

Comments
 (0)