Skip to main content

main_loop_async/
platform.rs

1//! Stores the wrapper functions that can be called from either native or wasm
2//! code
3
4#[cfg(not(target_arch = "wasm32"))]
5mod native;
6#[cfg(target_arch = "wasm32")]
7mod wasm;
8
9// Using * imports to bring them up to this level
10#[cfg(not(target_arch = "wasm32"))]
11pub use native::*;
12#[cfg(target_arch = "wasm32")]
13pub use wasm::*;
14
15use crate::{Spawnable, SpawnableWithReturn};
16
17/// Spawns a async job to run `f` (the future passed) and returns a
18/// [`futures::channel::oneshot::Receiver`] which can be used to get the return
19/// value from `f`.
20///
21/// See the examples [folder](https://github.com/c-git/reqwest-cross/tree/main/examples)
22/// for more complete examples.
23///
24/// # Example
25/// ```rust
26/// # use main_loop_async::spawn_with_return;
27///
28/// # #[cfg(all(not(target_arch = "wasm32"),feature = "native-tokio"))]
29/// # #[tokio::main(flavor = "current_thread")]
30/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
31///  let task = async || { "hi".to_owned() };
32///  let rx = spawn_with_return(task);
33///
34///  let result = rx.await?; //Only an example, in a real use case use try_recv instead
35///  assert_eq!(result, "hi");
36/// # Ok(())
37/// # }
38///
39/// # #[cfg(target_arch = "wasm32")]
40/// # fn main(){}
41/// ```
42pub fn spawn_with_return<F: SpawnableWithReturn<Out>, Out: Spawnable>(
43    f: F,
44) -> futures::channel::oneshot::Receiver<<Out as Future>::Output> {
45    let (tx, rx) = futures::channel::oneshot::channel();
46    spawn(async move {
47        let result = f().await;
48        let result = tx.send(result);
49        if let Err(err_msg) = result {
50            tracing::error!("failed to send result from `spawn_with_return`: {err_msg:?}");
51        }
52    });
53    rx
54}