I tried to apply the observer pattern to Rust. As in other GC languages ββsuch as JS or Java, I wanted to send data links to the Observable in an event on the Observer . But the compiler continued to give me a headache due to check verification. Therefore, because of this, I learned about the use of Rc , but this did not allow me to change the value in Observable , then I used RefCell for internal variability, which worked the way I wanted. Hoorah, I said. But then I realized that Rc leads to the fact that one place can be sent from different places, which made the Observer event system obsolete. Therefore, after removing the event method from Observer I got:
struct Observable<T: Clone> { value: Rc<RefCell<T>> } impl<T: Clone> Observable<T> { fn new(value: T) -> Observable<T> { Observable { value: Rc::new(RefCell::new(value)) } } fn set_value(&mut self, value: T) { *self.value.borrow_mut() = value; } fn register(&mut self) -> Observer<T> { Observer::new(self.value.clone()) } } struct Observer<T: Clone> { value: Rc<RefCell<T>> } impl<T: Clone> Observer<T> { fn new(value: Rc<RefCell<T>>) -> Observer<T> { Observer { value } } fn value(&self) -> T { (*self.value.borrow()).clone() } }
Link to Rust Playground
So the above code is an observer pattern from a technical point of view? Because otherwise it works for me. But just wanted to know what an observer pattern is?
source share