Update observer implementation
This commit is contained in:
parent
920ed044c6
commit
bd64bbde24
|
@ -7,33 +7,43 @@ pub trait Observer {
|
||||||
|
|
||||||
pub struct GatewayEvent<'a> {
|
pub struct GatewayEvent<'a> {
|
||||||
observers: Vec<&'a dyn Observer>,
|
observers: Vec<&'a dyn Observer>,
|
||||||
test_content: String,
|
pub test_content: String,
|
||||||
|
pub is_observed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> GatewayEvent<'a> {
|
impl<'a> GatewayEvent<'a> {
|
||||||
pub fn new(test_content: String) -> Self {
|
fn new(test_content: String) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
is_observed: false,
|
||||||
observers: Vec::new(),
|
observers: Vec::new(),
|
||||||
test_content,
|
test_content,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_observed(&self) -> bool {
|
||||||
|
self.is_observed
|
||||||
|
}
|
||||||
|
|
||||||
pub fn subscribe(&mut self, observable: &'a dyn Observer) {
|
pub fn subscribe(&mut self, observable: &'a dyn Observer) {
|
||||||
|
if self.is_observed {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.is_observed = true;
|
||||||
self.observers.push(observable)
|
self.observers.push(observable)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unsubscribe(&mut self, observable: &'a dyn Observer) {
|
pub fn unsubscribe(&mut self, observable: &'a dyn Observer) {
|
||||||
if let Some(index) = self.observers.iter().position(|&o| o == observable) {
|
self.observers.pop();
|
||||||
self.observers.remove(index);
|
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.test_content = test_content;
|
||||||
self.notify();
|
self.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notify(&self) {
|
fn notify(&self) {
|
||||||
for observer in &self.observers {
|
for observer in &self.observers {
|
||||||
observer.update(&self.test_content);
|
observer.update(&self.test_content);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue