Skip to main content

Async

Enum Async 

Source
pub enum Async<T: Clone> {
    Loading,
    Ready(T),
    Error(String),
}
Expand description

Represents the state of an async operation.

Variants§

§

Loading

The operation is still loading.

§

Ready(T)

The operation completed successfully.

§

Error(String)

The operation failed with an error.

Implementations§

Source§

impl<T: Clone> Async<T>

Source

pub fn is_loading(&self) -> bool

Returns true if the async operation is still loading.

Examples found in repository?
examples/24_async_data.rs (line 136)
38    fn render(&self, cx: Scope) -> View {
39        let show_help = state!(cx, || false);
40
41        // F1 toggles help
42        cx.use_command(
43            KeyBinding::key(KeyCode::F(1)),
44            with!(show_help => move || show_help.update(|v| *v = !*v)),
45        );
46
47        // Simulate fetching user profile (slow - 2 seconds)
48        let profile = async_data!(cx, || {
49            thread::sleep(Duration::from_secs(2));
50            Ok(UserProfile {
51                name: "Alice Johnson".to_string(),
52                email: "alice@example.com".to_string(),
53                member_since: "January 2024".to_string(),
54            })
55        });
56
57        // Simulate fetching user stats (medium - 1 second)
58        let stats = async_data!(cx, || {
59            thread::sleep(Duration::from_secs(1));
60            Ok(Stats {
61                posts: 142,
62                followers: 1234,
63                following: 567,
64            })
65        });
66
67        // Simulate a failing request
68        let failing_data = async_data!(cx, || {
69            thread::sleep(Duration::from_millis(500));
70            Err::<String, _>("Network error: Connection refused".to_string())
71        });
72
73        View::vstack()
74            .spacing(1)
75            .child(
76                // Header
77                View::boxed()
78                    .border(true)
79                    .padding(1)
80                    .child(
81                        View::vstack()
82                            .child(View::styled_text("Async Data Loading Demo").bold().build())
83                            .child(
84                                View::styled_text(
85                                    "Demonstrates use_async for loading data with loading/error states",
86                                )
87                                .dim()
88                                .build(),
89                            )
90                            .build(),
91                    )
92                    .build(),
93            )
94            .child(
95                // Main content - three columns
96                View::hstack()
97                    .spacing(1)
98                    // Profile section
99                    .child(
100                        View::boxed()
101                            .flex(1)
102                            .border(true)
103                            .padding(1)
104                            .child(render_profile_section(&profile))
105                            .build(),
106                    )
107                    // Stats section
108                    .child(
109                        View::boxed()
110                            .flex(1)
111                            .border(true)
112                            .padding(1)
113                            .child(render_stats_section(&stats))
114                            .build(),
115                    )
116                    // Error section
117                    .child(
118                        View::boxed()
119                            .flex(1)
120                            .border(true)
121                            .padding(1)
122                            .child(render_error_section(&failing_data))
123                            .build(),
124                    )
125                    .build(),
126            )
127            .child(
128                // Status footer
129                View::boxed()
130                    .border(true)
131                    .padding(1)
132                    .child(
133                        View::vstack()
134                            .child(View::text(format!(
135                                "Overall status: {}",
136                                if profile.is_loading() || stats.is_loading() {
137                                    "Loading..."
138                                } else if profile.is_error() || stats.is_error() || failing_data.is_error() {
139                                    "Some requests failed"
140                                } else {
141                                    "All data loaded"
142                                }
143                            )))
144                            .child(View::styled_text("F1 help • Ctrl+Q quit").dim().build())
145                            .build(),
146                    )
147                    .build(),
148            )
149            .child(
150                View::modal()
151                    .visible(show_help.get())
152                    .title("Example 24: Async Data")
153                    .on_dismiss(with!(show_help => move || show_help.set(false)))
154                    .child(
155                        View::vstack()
156                            .child(View::styled_text("What you're seeing").bold().build())
157                            .child(View::text("• Three async data loads in parallel"))
158                            .child(View::text("• Loading, success, and error states"))
159                            .child(View::text("• Different load times for each"))
160                            .child(View::gap(1))
161                            .child(View::styled_text("Key concepts").bold().build())
162                            .child(View::text("• async_data!() macro runs in background"))
163                            .child(View::text("• Returns Async<T> enum"))
164                            .child(View::text("• .is_loading() / .is_error() helpers"))
165                            .child(View::text("• Pattern match for state handling"))
166                            .child(View::gap(1))
167                            .child(View::styled_text("Try this").bold().build())
168                            .child(View::text("• Watch data load progressively"))
169                            .child(View::text("• Notice the failing request"))
170                            .child(View::gap(1))
171                            .child(View::styled_text("Next up").bold().build())
172                            .child(View::text("→ 25_context: context API"))
173                            .child(View::gap(1))
174                            .child(View::styled_text("Press Escape to close").dim().build())
175                            .build()
176                    )
177                    .build()
178            )
179            .build()
180    }
Source

pub fn is_ready(&self) -> bool

Returns true if the async operation completed successfully.

Source

pub fn is_error(&self) -> bool

Returns true if the async operation failed.

Examples found in repository?
examples/24_async_data.rs (line 138)
38    fn render(&self, cx: Scope) -> View {
39        let show_help = state!(cx, || false);
40
41        // F1 toggles help
42        cx.use_command(
43            KeyBinding::key(KeyCode::F(1)),
44            with!(show_help => move || show_help.update(|v| *v = !*v)),
45        );
46
47        // Simulate fetching user profile (slow - 2 seconds)
48        let profile = async_data!(cx, || {
49            thread::sleep(Duration::from_secs(2));
50            Ok(UserProfile {
51                name: "Alice Johnson".to_string(),
52                email: "alice@example.com".to_string(),
53                member_since: "January 2024".to_string(),
54            })
55        });
56
57        // Simulate fetching user stats (medium - 1 second)
58        let stats = async_data!(cx, || {
59            thread::sleep(Duration::from_secs(1));
60            Ok(Stats {
61                posts: 142,
62                followers: 1234,
63                following: 567,
64            })
65        });
66
67        // Simulate a failing request
68        let failing_data = async_data!(cx, || {
69            thread::sleep(Duration::from_millis(500));
70            Err::<String, _>("Network error: Connection refused".to_string())
71        });
72
73        View::vstack()
74            .spacing(1)
75            .child(
76                // Header
77                View::boxed()
78                    .border(true)
79                    .padding(1)
80                    .child(
81                        View::vstack()
82                            .child(View::styled_text("Async Data Loading Demo").bold().build())
83                            .child(
84                                View::styled_text(
85                                    "Demonstrates use_async for loading data with loading/error states",
86                                )
87                                .dim()
88                                .build(),
89                            )
90                            .build(),
91                    )
92                    .build(),
93            )
94            .child(
95                // Main content - three columns
96                View::hstack()
97                    .spacing(1)
98                    // Profile section
99                    .child(
100                        View::boxed()
101                            .flex(1)
102                            .border(true)
103                            .padding(1)
104                            .child(render_profile_section(&profile))
105                            .build(),
106                    )
107                    // Stats section
108                    .child(
109                        View::boxed()
110                            .flex(1)
111                            .border(true)
112                            .padding(1)
113                            .child(render_stats_section(&stats))
114                            .build(),
115                    )
116                    // Error section
117                    .child(
118                        View::boxed()
119                            .flex(1)
120                            .border(true)
121                            .padding(1)
122                            .child(render_error_section(&failing_data))
123                            .build(),
124                    )
125                    .build(),
126            )
127            .child(
128                // Status footer
129                View::boxed()
130                    .border(true)
131                    .padding(1)
132                    .child(
133                        View::vstack()
134                            .child(View::text(format!(
135                                "Overall status: {}",
136                                if profile.is_loading() || stats.is_loading() {
137                                    "Loading..."
138                                } else if profile.is_error() || stats.is_error() || failing_data.is_error() {
139                                    "Some requests failed"
140                                } else {
141                                    "All data loaded"
142                                }
143                            )))
144                            .child(View::styled_text("F1 help • Ctrl+Q quit").dim().build())
145                            .build(),
146                    )
147                    .build(),
148            )
149            .child(
150                View::modal()
151                    .visible(show_help.get())
152                    .title("Example 24: Async Data")
153                    .on_dismiss(with!(show_help => move || show_help.set(false)))
154                    .child(
155                        View::vstack()
156                            .child(View::styled_text("What you're seeing").bold().build())
157                            .child(View::text("• Three async data loads in parallel"))
158                            .child(View::text("• Loading, success, and error states"))
159                            .child(View::text("• Different load times for each"))
160                            .child(View::gap(1))
161                            .child(View::styled_text("Key concepts").bold().build())
162                            .child(View::text("• async_data!() macro runs in background"))
163                            .child(View::text("• Returns Async<T> enum"))
164                            .child(View::text("• .is_loading() / .is_error() helpers"))
165                            .child(View::text("• Pattern match for state handling"))
166                            .child(View::gap(1))
167                            .child(View::styled_text("Try this").bold().build())
168                            .child(View::text("• Watch data load progressively"))
169                            .child(View::text("• Notice the failing request"))
170                            .child(View::gap(1))
171                            .child(View::styled_text("Next up").bold().build())
172                            .child(View::text("→ 25_context: context API"))
173                            .child(View::gap(1))
174                            .child(View::styled_text("Press Escape to close").dim().build())
175                            .build()
176                    )
177                    .build()
178            )
179            .build()
180    }
Source

pub fn get(&self) -> Option<&T>

Returns the value if ready, or None otherwise.

Source

pub fn unwrap_or(&self, default: T) -> T

Returns the value if ready, or a default.

Source

pub fn unwrap_or_else(&self, f: impl FnOnce() -> T) -> T

Returns the value if ready, or computes a default.

Trait Implementations§

Source§

impl<T: Clone + Clone> Clone for Async<T>

Source§

fn clone(&self) -> Async<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Async<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Async<T>
where T: RefUnwindSafe,

§

impl<T> Send for Async<T>
where T: Send,

§

impl<T> Sync for Async<T>
where T: Sync,

§

impl<T> Unpin for Async<T>
where T: Unpin,

§

impl<T> UnwindSafe for Async<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.