3 releases (stable)

1.1.0 Jul 13, 2024
1.0.0 Jul 13, 2024

#272 in Concurrency

Download history 77/week @ 2024-07-20 105/week @ 2024-07-27 42/week @ 2024-08-03 17/week @ 2024-08-10 61/week @ 2024-08-17 77/week @ 2024-08-24 5/week @ 2024-08-31 43/week @ 2024-09-14 46/week @ 2024-09-21 70/week @ 2024-09-28 96/week @ 2024-10-05 53/week @ 2024-10-12 32/week @ 2024-10-19 55/week @ 2024-10-26 23/week @ 2024-11-02

177 downloads per month
Used in chorus

MPL-2.0 license

14KB
121 lines

pubserve

Publish and observe.

Simple, generic observer pattern implementation for Rust.

Usage

pubserve is really simple to use. Start by creating a Publisher for your data type:

use pubserve::Publisher;

let publisher = Publisher::<i32>::new();

Then, create a subscriber that will listen to the publisher:

use pubserve::Subscriber;

struct MySubscriber;

impl Subscriber<i32> for MySubscriber {
    fn update(&self, message: &i32) {
        // Do whatever you want with the data!
        println!("Received data: {}", message);
    }
}

Finally, subscribe the observer to the publisher:

use pubserve::ReferenceCounted;

let observer = MySubscriber;
let reference = ReferenceCounted::new(&observer);
publisher.subscribe(reference);

Now, whenever you publish data, all subscribed observers will be notified:

publisher.publish(42);
// STDOUT: "Received data: 42"

Unsubscribing is just as easy:

publisher.unsubscribe(reference);
publisher.publish(42);
// Nothing will be printed

It is of course possible to have multiple implementations of Subscriber be subscribed to the same Publisher. All of them will be notified immediately when data is published.

Features

No features are enabled by default. The following features are available:

Feature Description
send Makes the Subscriber trait Send and thus thread-safe.
async Makes the Subscriber trait Sync and async via the async_trait crate. Additionally, makes the publishing method async by extension

The send and async features can both be enabled at the same time, but do not have to be, should you only need one of them.

License

This project is licensed under the MPL-2.0 license. See the LICENSE file for more information. By committing to this repository, you agree to license your contributions under the MPL-2.0 license.

Dependencies

~115KB