mirror of
https://github.com/danbulant/cushy
synced 2026-06-11 02:20:54 +00:00
Added background-tasks example
This commit is contained in:
parent
27d5594776
commit
25d1caa1ea
2 changed files with 58 additions and 1 deletions
56
examples/background-tasks.rs
Normal file
56
examples/background-tasks.rs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
//! This example shows how dynamic values make it easy to communicate state back
|
||||
//! to widgets from multiple threads.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use gooey::animation::ZeroToOne;
|
||||
use gooey::value::{Dynamic, Switchable};
|
||||
use gooey::widget::MakeWidget;
|
||||
use gooey::widgets::progress::{Progress, Progressable};
|
||||
use gooey::Run;
|
||||
|
||||
#[derive(Debug, Default, Eq, PartialEq)]
|
||||
struct Task {
|
||||
progress: Dynamic<Progress>,
|
||||
}
|
||||
|
||||
fn main() -> gooey::Result {
|
||||
let task = Dynamic::new(None::<Task>);
|
||||
|
||||
task.switcher(|task, dynamic| {
|
||||
if let Some(task) = task {
|
||||
// A background thread is running, show a progress bar.
|
||||
task.progress.clone().progress_bar().make_widget()
|
||||
} else {
|
||||
// There is no background task. Show a button that will start one.
|
||||
"Start"
|
||||
.into_button()
|
||||
.on_click({
|
||||
let task = dynamic.clone();
|
||||
move |()| {
|
||||
let background_task = Task::default();
|
||||
spawn_background_thread(&background_task.progress, &task);
|
||||
task.set(Some(background_task));
|
||||
}
|
||||
})
|
||||
.make_widget()
|
||||
}
|
||||
})
|
||||
.contain()
|
||||
.centered()
|
||||
.run()
|
||||
}
|
||||
|
||||
fn spawn_background_thread(progress: &Dynamic<Progress>, task: &Dynamic<Option<Task>>) {
|
||||
let progress = progress.clone();
|
||||
let task = task.clone();
|
||||
std::thread::spawn(move || background_task(&progress, &task));
|
||||
}
|
||||
|
||||
fn background_task(progress: &Dynamic<Progress>, task: &Dynamic<Option<Task>>) {
|
||||
for i in 0_u8..=10 {
|
||||
progress.set(Progress::Percent(ZeroToOne::new(f32::from(i) / 10.)));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
task.set(None);
|
||||
}
|
||||
|
|
@ -52,9 +52,10 @@ impl ProgressBar {
|
|||
}
|
||||
|
||||
/// A measurement of progress for an indicator widget like [`ProgressBar`].
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
|
||||
pub enum Progress<T = ZeroToOne> {
|
||||
/// The task has an indeterminant length.
|
||||
#[default]
|
||||
Indeterminant,
|
||||
/// The task is a specified amount complete.
|
||||
Percent(T),
|
||||
|
|
|
|||
Loading…
Reference in a new issue