Skip to content

Latest commit

 

History

History
91 lines (72 loc) · 3.18 KB

File metadata and controls

91 lines (72 loc) · 3.18 KB

Executing Custom Tasks

Tasks can run concurrently, and this allows us to perform asynchronous operations, like fetching data.

Iced offers three mutually exclusive features for that. They need to be enabled before usage:

Depending on your choice, your must also add the dependency crate to your Cargo.toml file:

The tokio crate is very popular, and we will use it as an example. First, we enable tokio feature and add tokio crate.

The dependencies of Cargo.toml should look like this:

[dependencies]
iced = { version = "0.13.1", features = ["tokio"] }
tokio = { version = "1.44.2", features = ["time"] }

For this example using tokio, we will use the tokio::time::sleep function. So the time feature is enabled.

We use Task::perform to execute an asynchronous function. The first parameter of Task::perform is an asynchronous function, and the second parameter is a function that returns Message. The Message will be produced once the asynchronous function is done.

In the following code, we use a simple asynchronous function tokio::time::sleep. When the asynchronous function finished, we will receive Message::Done. Don't worry too much about the details of the asynchronous function.

use iced::{
    Task,
    widget::{button, column, text},
};
use std::time::Duration;

fn main() -> iced::Result {
    iced::application("My App", MyApp::update, MyApp::view).run_with(MyApp::new)
}

#[derive(Debug, Clone)]
enum Message {
    Execute,
    Done,
}

#[derive(Default)]
struct MyApp {
    state: String,
}

impl MyApp {
    fn new() -> (Self, Task<Message>) {
        (
            Self {
                state: "Ready".into(),
            },
            Task::none(),
        )
    }

    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::Execute => {
                self.state = "Executing".into();
                return Task::perform(tokio::time::sleep(Duration::from_secs(1)), |_| {
                    Message::Done
                });
            }
            Message::Done => self.state = "Done".into(),
        }
        Task::none()
    }

    fn view(&self) -> iced::Element<Message> {
        column![
            button("Execute").on_press(Message::Execute),
            text(self.state.as_str()),
        ]
        .into()
    }
}

Executing custom tasks

➡️ Next: Windows

📘 Back: Table of contents