#observer #watch

drying_paint

Implementation of observer pattern for Rust

11 releases

0.5.2 Jul 16, 2022
0.5.0 Nov 6, 2021
0.4.7 Jun 19, 2021
0.4.5 Sep 18, 2020
0.1.0 Nov 30, 2019

#282 in Data structures

Download history 2/week @ 2022-11-28 7/week @ 2022-12-05 16/week @ 2022-12-12 7/week @ 2022-12-19 5/week @ 2022-12-26 2/week @ 2023-01-02 7/week @ 2023-01-09 6/week @ 2023-01-16 19/week @ 2023-01-23 13/week @ 2023-01-30 95/week @ 2023-02-06 62/week @ 2023-02-13 45/week @ 2023-02-20 6/week @ 2023-02-27 5/week @ 2023-03-06 3/week @ 2023-03-13

80 downloads per month
Used in suzy

Apache-2.0 OR MIT OR Zlib

62KB
1.5K SLoC

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!");
    });
}

No runtime deps

Features

  • std