Skip to content

Commit 2d9fef6

Browse files
committed
use_async refactor, spawn method
1 parent 028a65d commit 2d9fef6

File tree

3 files changed

+23
-10
lines changed

3 files changed

+23
-10
lines changed

packages/iocraft/src/handler.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/// `Handler` is a type representing an optional event handler, commonly used for properties such as [`BoxProps::on_click`](crate::components::BoxProps::on_click).
1+
/// `Handler` is a type representing an optional event handler, commonly used for component properties.
22
#[derive(Default)]
33
pub enum Handler<'a, T> {
44
/// No handler is set.

packages/iocraft/src/hooks/use_async.rs

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@ use std::{
1010
/// component. When the component is unmounted, the tasks will be dropped.
1111
#[derive(Default)]
1212
pub struct UseAsync {
13-
once_fut: Option<BoxFuture<'static, ()>>,
13+
did_spawn_once: bool,
14+
futures: Vec<BoxFuture<'static, ()>>,
1415
}
1516

1617
impl Hook for UseAsync {
1718
fn poll_change(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
18-
match self.once_fut.as_mut() {
19-
Some(f) => f.as_mut().poll(cx),
20-
None => Poll::Pending,
21-
}
19+
self.futures
20+
.retain_mut(|f| !matches!(f.as_mut().poll(cx), Poll::Ready(())));
21+
Poll::Pending
2222
}
2323
}
2424

@@ -33,8 +33,21 @@ impl UseAsync {
3333
F: FnOnce() -> T,
3434
T: Future<Output = ()> + Send + 'static,
3535
{
36-
if self.once_fut.is_none() {
37-
self.once_fut = Some(Box::pin(f()));
36+
if !self.did_spawn_once {
37+
self.futures.push(Box::pin(f()));
38+
self.did_spawn_once = true;
3839
}
3940
}
41+
42+
/// Spawns a future which is bound to the lifetime of the component. When the component is
43+
/// unmounted, the future will be dropped.
44+
///
45+
/// The future will be spawned every time this function is called. If you need to run a future
46+
/// in the background, use [`spawn_once`](UseAsync::spawn_once) instead.
47+
pub fn spawn<F, T>(&mut self, f: F)
48+
where
49+
F: Future<Output = ()> + Send + 'static,
50+
{
51+
self.futures.push(Box::pin(f));
52+
}
4053
}

packages/iocraft/src/style.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ pub use taffy::style::{
1313
};
1414

1515
/// Defines a type that represents a percentage [0.0-100.0] and is convertible to any of the
16-
/// libary's other percent types. As a shorthand, you can express this in the [`element!`] macro
17-
/// using the `pct` suffix, e.g. `50pct`.
16+
/// libary's other percent types. As a shorthand, you can express this in the
17+
/// [`element!`](crate::element!) macro using the `pct` suffix, e.g. `50pct`.
1818
#[derive(Clone, Copy, Debug, Default, PartialEq)]
1919
pub struct Percent(pub f32);
2020

0 commit comments

Comments
 (0)