Skip to main content

main_loop_async/platform/
native.rs

1//! Stores the code specific to native compilations
2// but the comments are for both because these are the ones that show on docs.rs
3
4#[cfg(not(feature = "native-tokio"))]
5compile_error!(
6    "Must chose a native runtime by enabling a feature flag. Right now only tokio is supported. If you have a different runtime that you want please create an issue on github."
7);
8
9/// Spawns a future on the underlying runtime in a cross platform way (NB: the
10/// Send bound is removed in WASM)
11#[cfg(feature = "native-tokio")]
12pub fn spawn<F: crate::SpawnableNoReturn>(future: F) {
13    tokio::spawn(future);
14}
15
16/// Spawns a thead to run a sync job returns a
17/// [`futures::channel::oneshot::Receiver`] which can be used to get the return
18/// value from `f`.
19///
20/// See the examples [folder](https://github.com/c-git/reqwest-cross/tree/main/examples)
21/// for more complete examples.
22///
23/// # Example
24/// ```rust
25/// # use main_loop_async::spawn_thread_with_return;
26///
27/// # #[cfg(all(not(target_arch = "wasm32"),feature = "native-tokio"))]
28/// # #[tokio::main(flavor = "current_thread")]
29/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
30///  let task = || { "hi".to_owned() };
31///  let rx = spawn_thread_with_return(task);
32///
33///  let result = rx.await?; //Only an example, in a real use case use try_recv instead
34///  assert_eq!(result, "hi");
35/// # Ok(())
36/// # }
37///
38/// # #[cfg(target_arch = "wasm32")]
39/// # fn main(){}
40/// ```
41pub fn spawn_thread_with_return<F, T>(f: F) -> futures::channel::oneshot::Receiver<T>
42where
43    F: FnOnce() -> T,
44    F: Send + 'static,
45    T: Send + 'static + std::fmt::Debug,
46{
47    let (tx, rx) = futures::channel::oneshot::channel();
48    std::thread::spawn(move || {
49        let task_result = f();
50        let result = tx.send(task_result);
51        if let Err(err_msg) = result {
52            tracing::error!("failed to send result from `spawn_thread_with_return`: {err_msg:?}");
53        }
54    });
55    rx
56}