drying_paint

Crates.iodrying_paint
lib.rsdrying_paint
version0.5.5
sourcesrc
created_at2019-11-30 22:54:48.649158
updated_at2024-01-21 03:32:26.142834
descriptionImplementation of observer pattern for Rust
homepagehttps://crates.io/crates/drying_paint
repositoryhttps://github.com/geeklint/drying_paint
max_upload_size
id185616
size99,613
Violet Leonard (geeklint)

documentation

README

crates.io docs.rs Build Status License

The name 'drying_paint' comes from the expression "watching paint dry". This module provides a system to "watch" some values for changes and run code whenever they change.

The typical usage is as follows: you first define a structure to hold data, including some "watched" data.

struct HelloData {
    name: Watched<String>,
    greeting: String,
}

Implementing the trait WatcherInit for that structure gives you an place to set-up the code that should run when a watched value changes.

impl WatcherInit for HelloData {
    fn init(watcher: &mut WatcherMeta<Self>) {
        watcher.watch(|root| {
            root.greeting = format!("Hello, {}!", root.name);
        });
    }
}

Normally you need to wrap the data struct in a Watcher, so it's common to alias the watcher type to cleanup the syntax a bit:

type Hello = Watcher<HelloData>;

Creating watchers and setting watched data needs to happen within a WatchContext. WatchContext::update_current() will cause all the pending watcher code to run.

fn main() {
    let mut ctx = WatchContext::new();
    ctx.with(|| {
        let mut obj = Hello::new();
        *obj.data_mut().name = "Rust".to_string();
        WatchContext::update_current();
        assert_eq!(obj.data().greeting, "Hello, Rust!");
    });
}
Commit count: 138

cargo fmt