Crates.io | simple-observable |
lib.rs | simple-observable |
version | 0.2.2 |
source | src |
created_at | 2022-02-09 14:11:37.949197 |
updated_at | 2022-02-11 20:32:44.288056 |
description | Simple observable pointer for mutable and immutable data |
homepage | |
repository | |
max_upload_size | |
id | 529720 |
size | 5,399 |
Adding a dependency: simple-observable = "0.2.2"
use simple_observable::Observable;
fn main() {
let a = 1;
println!("Initial value: {}", a);
let mut obs1 = Observable::new(a);
obs1.add_listener(listener1);
obs1.add_listener(listener2);
obs1.add_listener(listener3);
obs1.change(my_change_function);
}
fn my_change_function(num: &mut i32) {
*num += 1;
}
fn listener1(num: &i32) {
println!("(listener1) New value after change: {}", num);
}
fn listener2(num: &i32) {
println!("(listener2) New value after change: {}", num);
}
fn listener3(num: &i32) {
println!("(listener3) New value after change: {}", num);
}
Observable
is a pointer that can be dereferenced and the data can be accessed directly. However, the data cannot be changed, but only read
It is important to understand that the Observable
owns the data and the only way to change the data is to call the change()
method.