Skip to main content

examples/observers/
observer_yield_existing.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7    pub x: f32,
8    pub y: f32,
9}
10
11// Observers can enable a "yield_existing" feature that upon creation of the
12// observer produces events for all entities that match the observer query. The
13// feature is only implemented for the builtin EcsOnAdd and EcsOnSet events.
14
15fn main() {
16    let world = World::new();
17
18    // Create existing entities with Position component
19    world.entity_named("e1").set(Position { x: 10.0, y: 20.0 });
20    world.entity_named("e2").set(Position { x: 20.0, y: 30.0 });
21
22    // Create an observer for three events
23    world
24        .observer::<flecs::OnSet, &Position>()
25        .yield_existing()
26        .each_iter(|it, index, pos| {
27            println!(
28                " - {}: {}: {}: {{ {}, {} }}",
29                it.event().name(),
30                it.event_id().to_str(),
31                it.entity(index),
32                pos.x,
33                pos.y
34            );
35        });
36
37    // Output:
38    //  - OnSet: Position: e1: { 10, 20 }
39    //  - OnSet: Position: e2: { 20, 30 }
40}
41
42#[cfg(feature = "flecs_nightly_tests")]
43#[test]
44fn test() {
45    let output_capture = OutputCapture::capture().unwrap();
46    main();
47    output_capture.test("observer_yield_existing".to_string());
48}