reactivate

Thread Safe Reactive Data Structure for Rust
Installation
include it in your Cargo.toml under [dependencies]
reactivate = { version = "*" }
Usage examples
Construction
use reactivate::Reactive;
fn main() {
let r = Reactive::new(10);
println!("{:?}", r); println!("{:?}", r.value()); }
Derive
use reactivate::Reactive;
fn main() {
let r = Reactive::new(10);
let d = r.derive(|val| val + 5);
println!("{:?}", r); println!("{:?}", d); }
Update
use reactivate::Reactive;
fn main() {
let r = Reactive::new(10);
let d = r.derive(|val| val + 5);
r.update(|_| 20);
println!("{:?}", r); println!("{:?}", d); }
Update Inplace
use reactivate::Reactive;
fn main() {
let r = Reactive::new(vec![1, 2, 3]);
let d = r.derive(|nums| nums.iter().sum::<i32>());
r.update_inplace(|nums| {
nums.push(4);
nums.push(5);
nums.push(6);
});
println!("{:?}", r); println!("{:?}", d); }
Merge and Derive
use reactivate::{Merge, Reactive};
fn main() {
let a = Reactive::new(String::from("hazash"));
let b = Reactive::new(0);
let d = (&a, &b)
.merge()
.derive(|(a_val, b_val)| a_val.len() + b_val);
println!("{:?}", a); println!("{:?}", b); println!("{:?}", d);
b.update(|_| 5);
println!("{:?}", a); println!("{:?}", b); println!("{:?}", d);
a.update(|_| String::from("mouse"));
println!("{:?}", a); println!("{:?}", b); println!("{:?}", d); }
Add Observers
use reactivate::Reactive;
use std::sync::{Arc, Mutex};
fn main() {
let r: Reactive<String> = Reactive::default();
let changes: Arc<Mutex<Vec<String>>> = Default::default();
r.add_observer({
let changes = changes.clone();
move |val| changes.lock().unwrap().push(val.clone())
});
r.update(|_| String::from("a"));
r.update_inplace(|s| {
s.push('b');
});
println!("{:?}", r); println!("{:?}", changes.lock().unwrap().clone()); }
With Threads
use reactivate::Reactive;
use std::{thread, time::Duration};
fn main() {
let r: Reactive<String> = Reactive::default();
let d = r.derive(|s| s.len());
let handle = thread::spawn({
let r = r.clone();
move || {
for _ in 0..10 {
r.update_inplace(|s| s.push('a'));
thread::sleep(Duration::from_millis(1));
}
}
});
for _ in 0..10 {
r.update_inplace(|s| s.push('b'));
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
println!("{:?}", r); println!("{:?}", d); }
Meta
M. Zahash – zahash.z@gmail.com
Distributed under the MIT license. See LICENSE for more information.
https://github.com/zahash/
Contributing
- Fork it (https://github.com/zahash/reactivate/fork)
- Create your feature branch (
git checkout -b feature/fooBar)
- Commit your changes (
git commit -am 'Add some fooBar')
- Push to the branch (
git push origin feature/fooBar)
- Create a new Pull Request