Crates.io | pubsub-bus |
lib.rs | pubsub-bus |
version | |
source | src |
created_at | 2025-01-29 19:29:19.897236 |
updated_at | 2025-02-04 19:15:04.817122 |
description | Thread-safe one-to-many publish-subscribe event system. Simple and easy to use. It just works (hopefully). |
homepage | |
repository | https://github.com/an-dr/pubsub-bus |
max_upload_size | |
id | 1535225 |
Cargo.toml error: | TOML parse error at line 18, column 1 | 18 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Thread-safe one-to-many event system. Simple and easy to use. It just works (hopefully).
Cargo.toml
pubsub-bus = "2.0.0"
pub enum Commands {
Atack { player_id: u32 },
Move { player_id: u32, x: f32, y: f32 },
}
let bus: Arc<EventBus<Commands>> = Arc::new(EventBus::new());;
impl Subscriber<Commands> for Player {
fn on_event(&mut self, event: &Event<Commands>) {
// Handle the event
}
}
...
let player1 = Arc::new(Mutex::new(Player { id: 1 }));
bus.add_subscriber(player1);
pub struct Input {
emitter: EventEmitter<Commands>,
}
impl Publisher<Commands> for Input {
fn get_mut_emitter(&mut self) -> &mut EventEmitter<Commands> {
&mut self.emitter
}
}
...
let mut input = Input::new();
bus.add_publisher(&mut input);
impl Input {
pub fn send_move(&self, player_id: u32, x: f32, y: f32) {
self.emitter.publish(Commands::Move { player_id, x, y });
}
}
The following example demonstrates how to exchange events between players and an input system.
fn main() {
// Create a shared bus. No mutex as the internal data is already thread-safe.
let bus: Arc<EventBus<Commands>> = Arc::new(EventBus::new());
// Players are subscribers = concurently accesible receivers of events.
// They have to be wrapped in Arc<Mutex<T>> to be thread-safe.
let player1 = Arc::new(Mutex::new(Player { id: 1 }));
let player2 = Arc::new(Mutex::new(Player { id: 2 }));
// Input is a publisher. It has to know to which bus it should publish events.
let mut input = Input::new();
// Subscribers will be added to the bus's list
bus.add_subscriber(player1);
bus.add_subscriber(player2);
// Bus will register itslef to the input
bus.add_publisher(&mut input);
// Send some events
input.send_move(1, 1.0, 2.0);
input.send_atack(2);
}
For the full example, see the examples/basic_game_events directory.