| 34 | |
| 35 | impl SingletonManager { |
| 36 | pub async fn get_or_init<T: Send + Sync + 'static, E>( |
| 37 | &self, |
| 38 | handle: &SingletonHandle, |
| 39 | init_func: impl Future<Output = Result<Arc<T>, E>> + Send, |
| 40 | ) -> Result<Arc<T>, E> { |
| 41 | let mut singletons = self.singletons.lock().await; |
| 42 | if singletons.len() < handle.slot + 1 { |
| 43 | singletons.resize(handle.slot + 1, None); |
| 44 | } |
| 45 | if let Some(singleton) = &singletons[handle.slot] |
| 46 | && let Some(singleton) = singleton.upgrade() |
| 47 | { |
| 48 | return Ok(singleton.clone().downcast().unwrap()); |
| 49 | } |
| 50 | |
| 51 | let to_insert = init_func.await?; |
| 52 | singletons[handle.slot] = Some(Arc::downgrade( |
| 53 | &(to_insert.clone() as Arc<dyn Any + Send + Sync>), |
| 54 | )); |
| 55 | Ok(to_insert) |
| 56 | } |
| 57 | } |