pub trait Message:
Send
+ Sync
+ 'static { }Expand description
A buffered message for pull-based event handling.
Messages can be written with MessageWriter and read using the MessageReader system parameter.
Messages are stored in the Messages<M> resource, and require periodically polling the world for new messages,
typically in a system that runs as part of a schedule.
A MessageReader system parameter tracks the consumption of these events on a per-system basis using a Local<MessageCursor>,
which will guarantee each system an opportunity to read the event once.
While the polling imposes a small overhead, messages are useful for efficiently batch processing
a large number of messages at once. For cases like these, messages can be more efficient than Events (which are handled via Observers).
Unlike Events triggered for observers, messages are evaluated at fixed points in the schedule
rather than immediately when they are sent. This allows for more predictable scheduling, and deferring
message processing to a later point in time.
Messages must be thread-safe.
§Usage
The Message trait can be derived:
#[derive(Message)]
struct Greeting(String);The message can then be written to the message buffer using a MessageWriter:
fn write_hello(mut writer: MessageWriter<Greeting>) {
writer.write(Greeting("Hello!".to_string()));
}Messages can be efficiently read using a MessageReader:
fn read_messages(mut reader: MessageReader<Greeting>) {
// Process all messages of type `Greeting`.
for Greeting(greeting) in reader.read() {
println!("{greeting}");
}
}Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".