Eliminate several singletons
just for better lifecycle management Signed-off-by: x1a0b0 <xbtseng@gmail.com>
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::future::Future;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
use crate::base::AppError;
|
||||
use crate::utils::shell::run_shell;
|
||||
use crate::utils::task::TaskManager;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
|
||||
pub enum PlayingMonitorEvent {
|
||||
@@ -13,10 +13,22 @@ pub enum PlayingMonitorEvent {
|
||||
Idle,
|
||||
}
|
||||
|
||||
pub struct PlayingMonitor;
|
||||
pub struct PlayingMonitor {
|
||||
task_holder: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Default for PlayingMonitor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayingMonitor {
|
||||
pub async fn start<F, Fut>(on_update: F)
|
||||
pub fn new() -> Self {
|
||||
Self { task_holder: None }
|
||||
}
|
||||
|
||||
pub async fn start<F, Fut>(&mut self, on_update: F)
|
||||
where
|
||||
F: Fn(PlayingMonitorEvent) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
|
||||
@@ -25,11 +37,16 @@ impl PlayingMonitor {
|
||||
let _ = PlayingMonitor::start_monitor(on_update).await;
|
||||
});
|
||||
|
||||
TaskManager::instance().add("PlayingMonitor", monitor).await;
|
||||
if let Some(old_task) = self.task_holder.replace(monitor) {
|
||||
println!("Aborting old playing monitor task");
|
||||
old_task.abort();
|
||||
};
|
||||
}
|
||||
|
||||
pub async fn stop() {
|
||||
TaskManager::instance().dispose("PlayingMonitor").await;
|
||||
pub async fn stop(&mut self) {
|
||||
if let Some(handle) = self.task_holder.take() {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_monitor<F, Fut>(on_update: F) -> Result<(), AppError>
|
||||
|
||||
Reference in New Issue
Block a user