poee/lib.rs
1pub use poee::spawn;
2pub use poee::spawn_blocking;
3pub use poee::sync_fn;
4#[allow(warnings)]
5pub mod poee{
6 use std::future::Future;
7 use tokio::runtime::Runtime;
8 use tokio::task::{JoinHandle, JoinError};
9 /// ### Spawns a new asynchronous task, returning a JoinHandle for it.
10 ///```rust
11 /// #[tokio::main]
12 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
13 /// poee::spawn(||{
14 /// std::fs::write("demo0", "rust").unwrap();
15 /// });
16 /// fn demo(){
17 /// std::fs::write("demo1", "rust").unwrap();
18 /// }
19 /// poee::spawn(demo);
20 ///
21 /// Ok(())
22 /// }
23 ///```
24 pub fn spawn<T:FnOnce() -> ()+ std::marker::Send + 'static>(function: T) -> JoinHandle<T::Output>
25 {
26 let task = tokio::spawn(async move {
27 function();
28 });
29 task
30 }
31 /// ### Runs the provided closure on a thread where blocking is acceptable.
32 /// ```rust
33 /// #[tokio::main]
34 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
35 /// poee::spawn_blocking(||{
36 /// std::fs::write("demo0", "rust").unwrap();
37 /// });
38 /// fn demo(){
39 /// std::fs::write("demo1", "rust").unwrap();
40 /// }
41 /// poee::spawn_blocking(demo);
42 ///
43 /// Ok(())
44 /// }
45 /// ```
46 pub fn spawn_blocking<T:FnOnce() -> ()+ std::marker::Send + 'static>(function: T) -> JoinHandle<T::Output>
47 {
48 let blocking_task = tokio::task::spawn_blocking(move || {
49 function();
50 });
51 blocking_task
52 }
53 /// ### executed on the async code in sync
54 /// ```rust
55 /// fn main(){
56 /// async fn demo(){
57 /// println!("demo");
58 /// }
59 /// poee::sync_fn(demo());
60 ///}
61 /// ```
62 pub fn sync_fn<T:Future+ std::marker::Send + 'static>(function: T){
63 // Create a new Tokio runtime
64 let rt = Runtime::new().unwrap();
65 // Run an async function in the runtime
66 rt.block_on(async {
67 function.await;
68 });
69 }
70}