Update observer implementation

This commit is contained in:
bitfl0wer 2023-04-27 22:29:07 +02:00
parent 920ed044c6
commit bd64bbde24
1 changed files with 17 additions and 7 deletions

View File

@ -7,33 +7,43 @@ pub trait Observer {
pub struct GatewayEvent<'a> {
observers: Vec<&'a dyn Observer>,
test_content: String,
pub test_content: String,
pub is_observed: bool,
}
impl<'a> GatewayEvent<'a> {
pub fn new(test_content: String) -> Self {
fn new(test_content: String) -> Self {
Self {
is_observed: false,
observers: Vec::new(),
test_content,
}
}
pub fn is_observed(&self) -> bool {
self.is_observed
}
pub fn subscribe(&mut self, observable: &'a dyn Observer) {
if self.is_observed {
return;
}
self.is_observed = true;
self.observers.push(observable)
}
pub fn unsubscribe(&mut self, observable: &'a dyn Observer) {
if let Some(index) = self.observers.iter().position(|&o| o == observable) {
self.observers.remove(index);
}
self.observers.pop();
self.is_observed = false;
return;
}
pub fn update_data(&mut self, test_content: String) {
fn update_data(&mut self, test_content: String) {
self.test_content = test_content;
self.notify();
}
pub fn notify(&self) {
fn notify(&self) {
for observer in &self.observers {
observer.update(&self.test_content);
}