bevy/examples/ecs/hotpatching_systems.rs
Joona Aalto e5dc177b4b
Rename Trigger to On (#19596)
# Objective

Currently, the observer API looks like this:

```rust
app.add_observer(|trigger: Trigger<Explode>| {
    info!("Entity {} exploded!", trigger.target());
});
```

Future plans for observers also include "multi-event observers" with a
trigger that looks like this (see [Cart's
example](https://github.com/bevyengine/bevy/issues/14649#issuecomment-2960402508)):

```rust
trigger: Trigger<(
    OnAdd<Pressed>,
    OnRemove<Pressed>,
    OnAdd<InteractionDisabled>,
    OnRemove<InteractionDisabled>,
    OnInsert<Hovered>,
)>,
```

In scenarios like this, there is a lot of repetition of `On`. These are
expected to be very high-traffic APIs especially in UI contexts, so
ergonomics and readability are critical.

By renaming `Trigger` to `On`, we can make these APIs read more cleanly
and get rid of the repetition:

```rust
app.add_observer(|trigger: On<Explode>| {
    info!("Entity {} exploded!", trigger.target());
});
```

```rust
trigger: On<(
    Add<Pressed>,
    Remove<Pressed>,
    Add<InteractionDisabled>,
    Remove<InteractionDisabled>,
    Insert<Hovered>,
)>,
```

Names like `On<Add<Pressed>>` emphasize the actual event listener nature
more than `Trigger<OnAdd<Pressed>>`, and look cleaner. This *also* frees
up the `Trigger` name if we want to use it for the observer event type,
splitting them out from buffered events (bikeshedding this is out of
scope for this PR though).

For prior art:
[`bevy_eventlistener`](https://github.com/aevyrie/bevy_eventlistener)
used
[`On`](https://docs.rs/bevy_eventlistener/latest/bevy_eventlistener/event_listener/struct.On.html)
for its event listener type. Though in our case, the observer is the
event listener, and `On` is just a type containing information about the
triggered event.

## Solution

Steal from `bevy_event_listener` by @aevyrie and use `On`.

- Rename `Trigger` to `On`
- Rename `OnAdd` to `Add`
- Rename `OnInsert` to `Insert`
- Rename `OnReplace` to `Replace`
- Rename `OnRemove` to `Remove`
- Rename `OnDespawn` to `Despawn`

## Discussion

### Naming Conflicts??

Using a name like `Add` might initially feel like a very bad idea, since
it risks conflict with `core::ops::Add`. However, I don't expect this to
be a big problem in practice.

- You rarely need to actually implement the `Add` trait, especially in
modules that would use the Bevy ECS.
- In the rare cases where you *do* get a conflict, it is very easy to
fix by just disambiguating, for example using `ops::Add`.
- The `Add` event is a struct while the `Add` trait is a trait (duh), so
the compiler error should be very obvious.

For the record, renaming `OnAdd` to `Add`, I got exactly *zero* errors
or conflicts within Bevy itself. But this is of course not entirely
representative of actual projects *using* Bevy.

You might then wonder, why not use `Added`? This would conflict with the
`Added` query filter, so it wouldn't work. Additionally, the current
naming convention for observer events does not use past tense.

### Documentation

This does make documentation slightly more awkward when referring to
`On` or its methods. Previous docs often referred to `Trigger::target`
or "sends a `Trigger`" (which is... a bit strange anyway), which would
now be `On::target` and "sends an observer `Event`".

You can see the diff in this PR to see some of the effects. I think it
should be fine though, we may just need to reword more documentation to
read better.
2025-06-12 18:22:33 +00:00

95 lines
2.9 KiB
Rust

//! This example demonstrates how to hot patch systems.
//!
//! It needs to be run with the dioxus CLI:
//! ```sh
//! dx serve --hot-patch --example hotpatching_systems --features hotpatching
//! ```
//!
//! All systems are automatically hot patchable.
//!
//! You can change the text in the `update_text` system, or the color in the
//! `on_click` system, and those changes will be hotpatched into the running
//! application.
//!
//! It's also possible to make any function hot patchable by wrapping it with
//! `bevy::dev_tools::hotpatch::call`.
use std::time::Duration;
use bevy::{color::palettes, prelude::*};
fn main() {
let (sender, receiver) = crossbeam_channel::unbounded::<()>();
// This function is here to demonstrate how to make something hot patchable outside of a system
// It uses a thread for simplicity but could be an async task, an asset loader, ...
start_thread(receiver);
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(TaskSender(sender))
.add_systems(Startup, setup)
.add_systems(Update, update_text)
.run();
}
fn update_text(mut text: Single<&mut Text>) {
// Anything in the body of a system can be changed.
// Changes to this string should be immediately visible in the example.
text.0 = "before".to_string();
}
fn on_click(
_click: On<Pointer<Click>>,
mut color: Single<&mut TextColor>,
task_sender: Res<TaskSender>,
) {
// Observers are also hot patchable.
// If you change this color and click on the text in the example, it will have the new color.
color.0 = palettes::tailwind::RED_600.into();
let _ = task_sender.0.send(());
}
#[derive(Resource)]
struct TaskSender(crossbeam_channel::Sender<()>);
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands
.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
..default()
},
children![(
Text::default(),
TextFont {
font_size: 100.0,
..default()
},
)],
))
.observe(on_click);
}
fn start_thread(receiver: crossbeam_channel::Receiver<()>) {
std::thread::spawn(move || {
while receiver.recv().is_ok() {
let start = bevy::platform::time::Instant::now();
// You can also make any part outside of a system hot patchable by wrapping it
// In this part, only the duration is hot patchable:
let duration = bevy::app::hotpatch::call(|| Duration::from_secs(2));
std::thread::sleep(duration);
info!("done after {:?}", start.elapsed());
}
});
}