kcl_lib/engine/async_tasks/
tasks.rs1use std::sync::Arc;
5
6use tokio::sync::RwLock;
7
8use crate::errors::KclError;
9
10#[derive(Debug, Clone)]
11pub struct AsyncTasks {
12 pub tasks: Arc<RwLock<tokio::task::JoinSet<anyhow::Result<(), KclError>>>>,
13}
14
15impl AsyncTasks {
16 pub fn new() -> Self {
17 Self {
18 tasks: Arc::new(RwLock::new(tokio::task::JoinSet::new())),
19 }
20 }
21
22 pub async fn spawn<F>(&mut self, task: F)
23 where
24 F: std::future::Future<Output = anyhow::Result<(), KclError>>,
25 F: Send + 'static,
26 {
27 self.tasks.write().await.spawn(task);
28 }
29
30 pub async fn join_all(&mut self) -> anyhow::Result<(), KclError> {
33 let tasks = std::mem::take(&mut *self.tasks.write().await);
34 let results = tasks.join_all().await;
35 for result in results {
36 result?;
37 }
38
39 Ok(())
40 }
41
42 pub async fn clear(&mut self) {
43 *self.tasks.write().await = tokio::task::JoinSet::new();
44 }
45}
46
47impl Default for AsyncTasks {
48 fn default() -> Self {
49 Self::new()
50 }
51}