freya_core/lifecycle/future_task.rs
1use crate::prelude::*;
2pub enum FutureState<D> {
3 /// Has not started loading yet.
4 Pending,
5 /// Currently loading.
6 Loading,
7 /// Finished loading and has data.
8 Fulfilled(D),
9}
10
11impl<D> FutureState<D> {
12 pub fn ok(&self) -> Option<&D> {
13 if let Self::Fulfilled(d) = &self {
14 Some(d)
15 } else {
16 None
17 }
18 }
19
20 pub fn unwrap(&self) -> &D {
21 self.ok().expect("Future state is not fulfilled")
22 }
23
24 pub fn is_loading(&self) -> bool {
25 matches!(self, Self::Loading)
26 }
27
28 pub fn is_pending(&self) -> bool {
29 matches!(self, Self::Pending)
30 }
31
32 pub fn is_fulfilled(&self) -> bool {
33 matches!(self, Self::Fulfilled(_))
34 }
35}
36
37pub struct FutureTask<D, F> {
38 future: State<Box<dyn FnMut() -> F>>,
39 state: State<FutureState<D>>,
40 task: State<Option<TaskHandle>>,
41}
42
43impl<D, F> Clone for FutureTask<D, F> {
44 fn clone(&self) -> Self {
45 *self
46 }
47}
48
49impl<D, F> Copy for FutureTask<D, F> {}
50
51impl<D: 'static, F: Future<Output = D> + 'static> FutureTask<D, F> {
52 /// Create a [FutureTask] with the given callback.
53 pub fn create(future: impl FnMut() -> F + 'static) -> FutureTask<D, F> {
54 Self {
55 future: State::create(Box::new(future)),
56 state: State::create(FutureState::Pending),
57 task: State::create(None),
58 }
59 }
60
61 /// Create a [FutureTask] with a reactive callback. Any [State] read inside the
62 /// callback (outside the async block) subscribes it, restarting the future when it changes.
63 pub fn create_reactive(mut future: impl FnMut() -> F + 'static) -> FutureTask<D, F> {
64 let (notify, reactive_context) = ReactiveContext::new_for_task();
65 let mut future_task =
66 Self::create(move || ReactiveContext::run(reactive_context.clone(), &mut future));
67 spawn(async move {
68 loop {
69 future_task.start();
70 notify.notified().await;
71 }
72 });
73 future_task
74 }
75
76 /// Cancel the currently task if there is any.
77 pub fn cancel(&mut self) {
78 if let Some(task) = self.task.take() {
79 task.cancel();
80 }
81 }
82
83 /// Start the [FutureTask]. If it was running already then it will be restarted.
84 pub fn start(&mut self) {
85 self.cancel();
86 let mut this = *self;
87 let task = spawn(async move {
88 let future = this.future.write()();
89 this.state.set(FutureState::Loading);
90 let data = future.await;
91 this.state.set(FutureState::Fulfilled(data));
92 });
93 self.task.set(Some(task));
94 }
95
96 /// Read the state of the [FutureTask]. See [FutureState].
97 pub fn read(&self) -> ReadRef<'_, FutureState<D>> {
98 self.state.read()
99 }
100
101 /// Get read-only access to the state of the [FutureTask].
102 pub fn state(&self) -> Readable<FutureState<D>> {
103 self.state.into_readable()
104 }
105}
106
107impl<D: 'static, F: Future<Output = D> + 'static> From<FutureTask<D, F>>
108 for Readable<FutureState<D>>
109{
110 fn from(value: FutureTask<D, F>) -> Self {
111 value.state()
112 }
113}
114
115impl<D: 'static, F: Future<Output = D> + 'static> IntoReadable<FutureState<D>>
116 for FutureTask<D, F>
117{
118 fn into_readable(self) -> Readable<FutureState<D>> {
119 self.into()
120 }
121}
122
123/// Create a [FutureTask] with the given callback.
124///
125/// This is a hook around [spawn] that exposes the progress of the future as
126/// reactive state, so you can render the pending, loading and fulfilled cases
127/// without managing the task by hand. It starts polling automatically.
128///
129/// ```rust,no_run
130/// # use freya::prelude::*;
131/// #[derive(PartialEq)]
132/// struct Greeting;
133///
134/// impl Component for Greeting {
135/// fn render(&self) -> impl IntoElement {
136/// let future = use_future(|| async {
137/// // Some async work...
138/// "Hello!".to_string()
139/// });
140///
141/// match &*future.read() {
142/// FutureState::Pending | FutureState::Loading => "Loading...".to_string(),
143/// FutureState::Fulfilled(text) => text.clone(),
144/// }
145/// }
146/// }
147/// ```
148///
149/// The callback is reactive, any [State] read inside of it (outside the async block)
150/// subscribes the future, restarting it when that state changes. Reads inside the
151/// async block do not subscribe.
152///
153/// ```rust,no_run
154/// # use freya::prelude::*;
155/// # async fn load_user(user_id: usize) -> String { String::new() }
156/// # fn app() -> impl IntoElement {
157/// let user_id = use_state(|| 1);
158///
159/// // Restarts whenever `user_id` changes.
160/// let user = use_future(move || {
161/// let user_id = user_id();
162/// async move { load_user(user_id).await }
163/// });
164/// # let _ = user;
165/// # rect()
166/// # }
167/// ```
168///
169/// To read its state use [FutureTask::read].
170/// You may restart/stop it using [FutureTask::start] and [FutureTask::cancel].
171pub fn use_future<D: 'static, F: Future<Output = D> + 'static>(
172 future: impl FnMut() -> F + 'static,
173) -> FutureTask<D, F> {
174 use_hook(|| FutureTask::create_reactive(future))
175}