1use std::cell::RefCell;
24use std::future::Future;
25use std::rc::Rc;
26
27use mgui_core::{LoadState, LoadStatus, Signal};
28use mgui_task::{TaskExecutor, TaskHandle};
29
30pub fn spawn_load<T, Fut>(tasks: &TaskExecutor, state: &Signal<LoadState<T>>, future: Fut) -> TaskHandle
34where
35 T: Clone + 'static,
36 Fut: Future<Output = Result<T, String>> + 'static,
37{
38 state.begin_load();
39 let signal = state.clone();
40 tasks.spawn_with(future, move |result| match result {
41 Ok(value) => signal.finish_load(value),
42 Err(message) => signal.fail_load(message),
43 })
44}
45
46#[derive(Clone)]
50pub struct LoadSlot<T: 'static> {
51 state: Signal<LoadState<T>>,
52 current: Rc<RefCell<Option<TaskHandle>>>,
53}
54
55impl<T: Clone + 'static> LoadSlot<T> {
56 pub fn new(state: Signal<LoadState<T>>) -> Self {
57 Self { state, current: Rc::new(RefCell::new(None)) }
58 }
59
60 pub fn state(&self) -> &Signal<LoadState<T>> {
62 &self.state
63 }
64
65 pub fn status(&self) -> LoadStatus {
66 self.state.get().status()
67 }
68
69 pub fn is_pending(&self) -> bool {
70 self.state.get().is_pending()
71 }
72
73 pub fn load<Fut, M>(&self, tasks: &TaskExecutor, make: M)
75 where
76 Fut: Future<Output = Result<T, String>> + 'static,
77 M: FnOnce() -> Fut,
78 {
79 self.cancel();
80 let handle = spawn_load(tasks, &self.state, make());
81 *self.current.borrow_mut() = Some(handle);
82 }
83
84 pub fn cancel(&self) {
86 if let Some(handle) = self.current.borrow_mut().take() {
87 handle.cancel();
88 }
89 self.state.update(|state| match state {
90 LoadState::Loading => *state = LoadState::Idle,
91 LoadState::Refreshing(data) => *state = LoadState::Ready(Rc::clone(data)),
92 _ => {}
93 });
94 }
95
96 pub fn finish(&self, value: T) {
98 self.cancel();
99 self.state.finish_load(value);
100 }
101
102 pub fn fail(&self, message: impl Into<Rc<str>>) {
104 self.cancel();
105 self.state.fail_load(message);
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use std::sync::{Arc, Mutex};
112 use std::time::Duration;
113
114 use super::*;
115 use mgui_core::LoadStatus;
116 use mgui_task::sleep;
117
118 fn executor() -> (TaskExecutor, Arc<Mutex<usize>>) {
119 let woke = Arc::new(Mutex::new(0usize));
120 let flag = Arc::clone(&woke);
121 (
122 TaskExecutor::new(Arc::new(move || {
123 *flag.lock().unwrap() += 1;
124 })),
125 woke,
126 )
127 }
128
129 fn drain(tasks: &TaskExecutor, state: &Signal<LoadState<Vec<String>>>) {
131 let start = std::time::Instant::now();
132 while state.get().is_pending() && start.elapsed() < Duration::from_secs(2) {
133 tasks.poll_ready();
134 std::thread::sleep(Duration::from_millis(2));
135 }
136 tasks.poll_ready();
137 }
138
139 #[test]
140 fn load_writes_ready_back_to_signal() {
141 let (tasks, _woke) = executor();
142 let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
143 let slot = LoadSlot::new(state.clone());
144
145 slot.load(&tasks, || async {
146 sleep(Duration::from_millis(5)).await;
147 Ok(vec!["alpha".to_string()])
148 });
149 assert_eq!(state.get().status(), LoadStatus::Loading, "发起后立即进入加载态");
150
151 drain(&tasks, &state);
152 assert_eq!(state.get().status(), LoadStatus::Ready);
153 assert_eq!(state.get().data().map(|d| d.len()), Some(1));
154 }
155
156 #[test]
157 fn failure_is_reported_as_error_status() {
158 let (tasks, _woke) = executor();
159 let state: Signal<LoadState<Vec<String>>> = LoadState::ready(vec!["old".to_string()]).signal();
160 let slot = LoadSlot::new(state.clone());
161
162 slot.load(&tasks, || async {
163 sleep(Duration::from_millis(5)).await;
164 Err("网络中断".to_string())
165 });
166 drain(&tasks, &state);
167
168 assert_eq!(state.get().message(), Some("网络中断"));
169 assert!(matches!(state.get().status(), LoadStatus::Error(_)));
170 assert_eq!(state.get().data().map(|d| d.len()), Some(1), "刷新失败仍保留旧数据");
171 }
172
173 #[test]
174 fn superseded_request_cannot_overwrite_the_newer_one() {
175 let (tasks, _woke) = executor();
176 let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
177 let slot = LoadSlot::new(state.clone());
178
179 slot.load(&tasks, || async {
181 sleep(Duration::from_millis(400)).await;
182 Ok(vec!["stale".to_string()])
183 });
184 slot.load(&tasks, || async {
185 sleep(Duration::from_millis(5)).await;
186 Ok(vec!["fresh".to_string()])
187 });
188 drain(&tasks, &state);
189
190 assert_eq!(state.get().data().map(|d| d[0].clone()), Some("fresh".to_string()));
191
192 let until = std::time::Instant::now() + Duration::from_millis(600);
194 while std::time::Instant::now() < until {
195 tasks.poll_ready();
196 std::thread::sleep(Duration::from_millis(5));
197 }
198 assert_eq!(state.get().data().map(|d| d[0].clone()), Some("fresh".to_string()), "被取消的任务不再回写");
199 }
200
201 #[test]
202 fn cancel_stops_reporting_pending() {
203 let (tasks, _woke) = executor();
204 let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
205 let slot = LoadSlot::new(state.clone());
206 slot.load(&tasks, || async {
207 sleep(Duration::from_millis(300)).await;
208 Ok(Vec::<String>::new())
209 });
210 assert!(slot.is_pending());
211 slot.cancel();
212 tasks.poll_ready();
213 assert!(!slot.is_pending());
214 }
215}