use std::cell::RefCell;
use std::future::Future;
use std::rc::Rc;
use mgui_core::{LoadState, LoadStatus, Signal};
use mgui_task::{TaskExecutor, TaskHandle};
pub fn spawn_load<T, Fut>(tasks: &TaskExecutor, state: &Signal<LoadState<T>>, future: Fut) -> TaskHandle
where
T: Clone + 'static,
Fut: Future<Output = Result<T, String>> + 'static,
{
state.begin_load();
let signal = state.clone();
tasks.spawn_with(future, move |result| match result {
Ok(value) => signal.finish_load(value),
Err(message) => signal.fail_load(message),
})
}
#[derive(Clone)]
pub struct LoadSlot<T: 'static> {
state: Signal<LoadState<T>>,
current: Rc<RefCell<Option<TaskHandle>>>,
}
impl<T: Clone + 'static> LoadSlot<T> {
pub fn new(state: Signal<LoadState<T>>) -> Self {
Self { state, current: Rc::new(RefCell::new(None)) }
}
pub fn state(&self) -> &Signal<LoadState<T>> {
&self.state
}
pub fn status(&self) -> LoadStatus {
self.state.get().status()
}
pub fn is_pending(&self) -> bool {
self.state.get().is_pending()
}
pub fn load<Fut, M>(&self, tasks: &TaskExecutor, make: M)
where
Fut: Future<Output = Result<T, String>> + 'static,
M: FnOnce() -> Fut,
{
self.cancel();
let handle = spawn_load(tasks, &self.state, make());
*self.current.borrow_mut() = Some(handle);
}
pub fn cancel(&self) {
if let Some(handle) = self.current.borrow_mut().take() {
handle.cancel();
}
self.state.update(|state| match state {
LoadState::Loading => *state = LoadState::Idle,
LoadState::Refreshing(data) => *state = LoadState::Ready(Rc::clone(data)),
_ => {}
});
}
pub fn finish(&self, value: T) {
self.cancel();
self.state.finish_load(value);
}
pub fn fail(&self, message: impl Into<Rc<str>>) {
self.cancel();
self.state.fail_load(message);
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::*;
use mgui_core::LoadStatus;
use mgui_task::sleep;
fn executor() -> (TaskExecutor, Arc<Mutex<usize>>) {
let woke = Arc::new(Mutex::new(0usize));
let flag = Arc::clone(&woke);
(
TaskExecutor::new(Arc::new(move || {
*flag.lock().unwrap() += 1;
})),
woke,
)
}
fn drain(tasks: &TaskExecutor, state: &Signal<LoadState<Vec<String>>>) {
let start = std::time::Instant::now();
while state.get().is_pending() && start.elapsed() < Duration::from_secs(2) {
tasks.poll_ready();
std::thread::sleep(Duration::from_millis(2));
}
tasks.poll_ready();
}
#[test]
fn load_writes_ready_back_to_signal() {
let (tasks, _woke) = executor();
let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
let slot = LoadSlot::new(state.clone());
slot.load(&tasks, || async {
sleep(Duration::from_millis(5)).await;
Ok(vec!["alpha".to_string()])
});
assert_eq!(state.get().status(), LoadStatus::Loading, "发起后立即进入加载态");
drain(&tasks, &state);
assert_eq!(state.get().status(), LoadStatus::Ready);
assert_eq!(state.get().data().map(|d| d.len()), Some(1));
}
#[test]
fn failure_is_reported_as_error_status() {
let (tasks, _woke) = executor();
let state: Signal<LoadState<Vec<String>>> = LoadState::ready(vec!["old".to_string()]).signal();
let slot = LoadSlot::new(state.clone());
slot.load(&tasks, || async {
sleep(Duration::from_millis(5)).await;
Err("网络中断".to_string())
});
drain(&tasks, &state);
assert_eq!(state.get().message(), Some("网络中断"));
assert!(matches!(state.get().status(), LoadStatus::Error(_)));
assert_eq!(state.get().data().map(|d| d.len()), Some(1), "刷新失败仍保留旧数据");
}
#[test]
fn superseded_request_cannot_overwrite_the_newer_one() {
let (tasks, _woke) = executor();
let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
let slot = LoadSlot::new(state.clone());
slot.load(&tasks, || async {
sleep(Duration::from_millis(400)).await;
Ok(vec!["stale".to_string()])
});
slot.load(&tasks, || async {
sleep(Duration::from_millis(5)).await;
Ok(vec!["fresh".to_string()])
});
drain(&tasks, &state);
assert_eq!(state.get().data().map(|d| d[0].clone()), Some("fresh".to_string()));
let until = std::time::Instant::now() + Duration::from_millis(600);
while std::time::Instant::now() < until {
tasks.poll_ready();
std::thread::sleep(Duration::from_millis(5));
}
assert_eq!(state.get().data().map(|d| d[0].clone()), Some("fresh".to_string()), "被取消的任务不再回写");
}
#[test]
fn cancel_stops_reporting_pending() {
let (tasks, _woke) = executor();
let state: Signal<LoadState<Vec<String>>> = LoadState::Idle.signal();
let slot = LoadSlot::new(state.clone());
slot.load(&tasks, || async {
sleep(Duration::from_millis(300)).await;
Ok(Vec::<String>::new())
});
assert!(slot.is_pending());
slot.cancel();
tasks.poll_ready();
assert!(!slot.is_pending());
}
}