freya/_docs/
async_tasks.rs

1//! # Async
2//!
3//! You may run asynchronous code through the different APIs Dioxus provide.
4//!
5//! Using third-party libraries such as tokio to spawn tasks could work but it's not recommended, these will not work with the lifecycling of the components.
6//!
7//! ### `spawn`
8//!
9//! With [`spawn`](dioxus_core::prelude::spawn) you can spawn an **async task** (Also known as green threads), this is primarily targeted for custom hooks or when you want to run some async code dynamically such as from an event listener.
10//!
11//! **Important:** Tasks spawned with `spawn` will be cancelled when the component their were created is dropped.
12//! If you want to have an async tasks not attached to the component you may use [`spawn_forever`](dioxus_core::prelude::spawn_forever).
13//!
14//! ```rust
15//! # use freya::prelude::*;
16//! fn app() -> Element {
17//!     rsx!(Button {
18//!         onclick: |_| {
19//!             if 1 == 1 {
20//!                 spawn(async move {
21//!                     println!("Hello, World fom an async task!");
22//!                 });
23//!             }
24//!         }
25//!     })
26//! }
27//! ```
28//!
29//! You can also use hooks like [`use_future`](dioxus::prelude::use_future) or [`use_resource`](dioxus::prelude::use_resource).