use bevy::prelude::*;
use std::sync::{Arc, RwLock};
use super::event_bus_backend::EventBusBackend;
use crate::runtime;
#[derive(Resource, Clone)]
pub struct EventBusBackendResource {
pub backend: Arc<RwLock<Box<dyn EventBusBackend>>>,
}
impl EventBusBackendResource {
pub fn new<B: EventBusBackend>(backend: B) -> Self {
Self {
backend: Arc::new(RwLock::new(Box::new(backend))),
}
}
pub fn from_box(boxed: Box<dyn EventBusBackend>) -> Self {
Self {
backend: Arc::new(RwLock::new(boxed)),
}
}
}
impl EventBusBackendResource {
pub fn read(&self) -> std::sync::RwLockReadGuard<'_, Box<dyn EventBusBackend>> {
self.backend.read().unwrap()
}
pub fn write(&self) -> std::sync::RwLockWriteGuard<'_, Box<dyn EventBusBackend>> {
self.backend.write().unwrap()
}
}
impl Drop for EventBusBackendResource {
fn drop(&mut self) {
if Arc::strong_count(&self.backend) != 1 {
return;
}
if let Ok(mut backend) = self.backend.write() {
let _ = runtime::block_on(backend.disconnect());
}
}
}