Refactor EventReader::iter to read (#9631)

# Objective

- The current `EventReader::iter` has been determined to cause confusion
among new Bevy users. It was suggested by @JoJoJet to rename the method
to better clarify its usage.
- Solves #9624 

## Solution

- Rename `EventReader::iter` to `EventReader::read`.
- Rename `EventReader::iter_with_id` to `EventReader::read_with_id`.
- Rename `ManualEventReader::iter` to `ManualEventReader::read`.
- Rename `ManualEventReader::iter_with_id` to
`ManualEventReader::read_with_id`.

---

## Changelog

- `EventReader::iter` has been renamed to `EventReader::read`.
- `EventReader::iter_with_id` has been renamed to
`EventReader::read_with_id`.
- `ManualEventReader::iter` has been renamed to
`ManualEventReader::read`.
- `ManualEventReader::iter_with_id` has been renamed to
`ManualEventReader::read_with_id`.
- Deprecated `EventReader::iter`
- Deprecated `EventReader::iter_with_id`
- Deprecated `ManualEventReader::iter`
- Deprecated `ManualEventReader::iter_with_id`

## Migration Guide

- Existing usages of `EventReader::iter` and `EventReader::iter_with_id`
will have to be changed to `EventReader::read` and
`EventReader::read_with_id` respectively.
- Existing usages of `ManualEventReader::iter` and
`ManualEventReader::iter_with_id` will have to be changed to
`ManualEventReader::read` and `ManualEventReader::read_with_id`
respectively.
This commit is contained in:
lelo 2023-08-30 10:20:03 -04:00 committed by GitHub
parent fb094eab87
commit 42e6dc8987
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
44 changed files with 108 additions and 82 deletions

View file

@ -94,7 +94,7 @@ impl Plugin for ScheduleRunnerPlugin {
if let Some(app_exit_events) = if let Some(app_exit_events) =
app.world.get_resource_mut::<Events<AppExit>>() app.world.get_resource_mut::<Events<AppExit>>()
{ {
if let Some(exit) = app_exit_event_reader.iter(&app_exit_events).last() if let Some(exit) = app_exit_event_reader.read(&app_exit_events).last()
{ {
return Err(exit.clone()); return Err(exit.clone());
} }

View file

@ -52,7 +52,7 @@ fn sending_system(mut event_writer: EventWriter<MyEvent>) {
// This system listens for events of the type MyEvent // This system listens for events of the type MyEvent
// If an event is received it will be printed to the console // If an event is received it will be printed to the console
fn receiving_system(mut event_reader: EventReader<MyEvent>) { fn receiving_system(mut event_reader: EventReader<MyEvent>) {
for my_event in event_reader.iter() { for my_event in event_reader.read() {
println!( println!(
" Received message {:?}, with random value of {}", " Received message {:?}, with random value of {}",
my_event.message, my_event.random_value my_event.message, my_event.random_value

View file

@ -403,13 +403,27 @@ impl<'w, 's, E: Event> EventReader<'w, 's, E> {
/// Iterates over the events this [`EventReader`] has not seen yet. This updates the /// Iterates over the events this [`EventReader`] has not seen yet. This updates the
/// [`EventReader`]'s event counter, which means subsequent event reads will not include events /// [`EventReader`]'s event counter, which means subsequent event reads will not include events
/// that happened before now. /// that happened before now.
pub fn read(&mut self) -> EventIterator<'_, E> {
self.reader.read(&self.events)
}
/// Iterates over the events this [`EventReader`] has not seen yet. This updates the
/// [`EventReader`]'s event counter, which means subsequent event reads will not include events
/// that happened before now.
#[deprecated = "use `.read()` instead."]
pub fn iter(&mut self) -> EventIterator<'_, E> { pub fn iter(&mut self) -> EventIterator<'_, E> {
self.reader.iter(&self.events) self.reader.read(&self.events)
}
/// Like [`read`](Self::read), except also returning the [`EventId`] of the events.
pub fn read_with_id(&mut self) -> EventIteratorWithId<'_, E> {
self.reader.read_with_id(&self.events)
} }
/// Like [`iter`](Self::iter), except also returning the [`EventId`] of the events. /// Like [`iter`](Self::iter), except also returning the [`EventId`] of the events.
#[deprecated = "use `.read_with_id() instead."]
pub fn iter_with_id(&mut self) -> EventIteratorWithId<'_, E> { pub fn iter_with_id(&mut self) -> EventIteratorWithId<'_, E> {
self.reader.iter_with_id(&self.events) self.reader.read_with_id(&self.events)
} }
/// Determines the number of events available to be read from this [`EventReader`] without consuming any. /// Determines the number of events available to be read from this [`EventReader`] without consuming any.
@ -545,12 +559,24 @@ impl<E: Event> Default for ManualEventReader<E> {
#[allow(clippy::len_without_is_empty)] // Check fails since the is_empty implementation has a signature other than `(&self) -> bool` #[allow(clippy::len_without_is_empty)] // Check fails since the is_empty implementation has a signature other than `(&self) -> bool`
impl<E: Event> ManualEventReader<E> { impl<E: Event> ManualEventReader<E> {
/// See [`EventReader::read`]
pub fn read<'a>(&'a mut self, events: &'a Events<E>) -> EventIterator<'a, E> {
self.read_with_id(events).without_id()
}
/// See [`EventReader::iter`] /// See [`EventReader::iter`]
#[deprecated = "use `.read()` instead."]
pub fn iter<'a>(&'a mut self, events: &'a Events<E>) -> EventIterator<'a, E> { pub fn iter<'a>(&'a mut self, events: &'a Events<E>) -> EventIterator<'a, E> {
self.iter_with_id(events).without_id() self.read_with_id(events).without_id()
}
/// See [`EventReader::read_with_id`]
pub fn read_with_id<'a>(&'a mut self, events: &'a Events<E>) -> EventIteratorWithId<'a, E> {
EventIteratorWithId::new(self, events)
} }
/// See [`EventReader::iter_with_id`] /// See [`EventReader::iter_with_id`]
#[deprecated = "use `.read_with_id() instead."]
pub fn iter_with_id<'a>(&'a mut self, events: &'a Events<E>) -> EventIteratorWithId<'a, E> { pub fn iter_with_id<'a>(&'a mut self, events: &'a Events<E>) -> EventIteratorWithId<'a, E> {
EventIteratorWithId::new(self, events) EventIteratorWithId::new(self, events)
} }
@ -834,7 +860,7 @@ mod tests {
events: &Events<E>, events: &Events<E>,
reader: &mut ManualEventReader<E>, reader: &mut ManualEventReader<E>,
) -> Vec<E> { ) -> Vec<E> {
reader.iter(events).cloned().collect::<Vec<E>>() reader.read(events).cloned().collect::<Vec<E>>()
} }
#[derive(Event, PartialEq, Eq, Debug)] #[derive(Event, PartialEq, Eq, Debug)]
@ -844,21 +870,21 @@ mod tests {
let mut events = Events::<E>::default(); let mut events = Events::<E>::default();
let mut reader = events.get_reader(); let mut reader = events.get_reader();
assert!(reader.iter(&events).next().is_none()); assert!(reader.read(&events).next().is_none());
events.send(E(0)); events.send(E(0));
assert_eq!(*reader.iter(&events).next().unwrap(), E(0)); assert_eq!(*reader.read(&events).next().unwrap(), E(0));
assert_eq!(reader.iter(&events).next(), None); assert_eq!(reader.read(&events).next(), None);
events.send(E(1)); events.send(E(1));
clear_func(&mut events); clear_func(&mut events);
assert!(reader.iter(&events).next().is_none()); assert!(reader.read(&events).next().is_none());
events.send(E(2)); events.send(E(2));
events.update(); events.update();
events.send(E(3)); events.send(E(3));
assert!(reader.iter(&events).eq([E(2), E(3)].iter())); assert!(reader.read(&events).eq([E(2), E(3)].iter()));
} }
#[test] #[test]
@ -880,7 +906,7 @@ mod tests {
events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]); events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]);
assert!(reader assert!(reader
.iter(&events) .read(&events)
.eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter())); .eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter()));
} }
@ -923,7 +949,7 @@ mod tests {
events.send(TestEvent { i: 1 }); events.send(TestEvent { i: 1 });
events.send(TestEvent { i: 2 }); events.send(TestEvent { i: 2 });
let mut reader = events.get_reader(); let mut reader = events.get_reader();
let mut iter = reader.iter(&events); let mut iter = reader.read(&events);
assert_eq!(iter.len(), 3); assert_eq!(iter.len(), 3);
iter.next(); iter.next();
assert_eq!(iter.len(), 2); assert_eq!(iter.len(), 2);
@ -994,13 +1020,13 @@ mod tests {
events.send(TestEvent { i: 0 }); events.send(TestEvent { i: 0 });
events.send(TestEvent { i: 1 }); events.send(TestEvent { i: 1 });
assert_eq!(reader.iter(&events).count(), 2); assert_eq!(reader.read(&events).count(), 2);
let mut old_events = Vec::from_iter(events.update_drain()); let mut old_events = Vec::from_iter(events.update_drain());
assert!(old_events.is_empty()); assert!(old_events.is_empty());
events.send(TestEvent { i: 2 }); events.send(TestEvent { i: 2 });
assert_eq!(reader.iter(&events).count(), 1); assert_eq!(reader.read(&events).count(), 1);
old_events.extend(events.update_drain()); old_events.extend(events.update_drain());
assert_eq!(old_events.len(), 2); assert_eq!(old_events.len(), 2);
@ -1028,7 +1054,7 @@ mod tests {
let mut schedule = Schedule::default(); let mut schedule = Schedule::default();
schedule.add_systems(|mut events: EventReader<TestEvent>| { schedule.add_systems(|mut events: EventReader<TestEvent>| {
let mut iter = events.iter(); let mut iter = events.read();
assert_eq!(iter.next(), Some(&TestEvent { i: 0 })); assert_eq!(iter.next(), Some(&TestEvent { i: 0 }));
assert_eq!(iter.nth(2), Some(&TestEvent { i: 3 })); assert_eq!(iter.nth(2), Some(&TestEvent { i: 3 }));
@ -1048,7 +1074,7 @@ mod tests {
let mut reader = let mut reader =
IntoSystem::into_system(|mut events: EventReader<TestEvent>| -> Option<TestEvent> { IntoSystem::into_system(|mut events: EventReader<TestEvent>| -> Option<TestEvent> {
events.iter().last().copied() events.read().last().copied()
}); });
reader.initialize(&mut world); reader.initialize(&mut world);

View file

@ -202,7 +202,7 @@ impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> {
/// that happened before now. /// that happened before now.
pub fn iter(&mut self) -> RemovedIter<'_> { pub fn iter(&mut self) -> RemovedIter<'_> {
self.reader_mut_with_events() self.reader_mut_with_events()
.map(|(reader, events)| reader.iter(events).cloned()) .map(|(reader, events)| reader.read(events).cloned())
.into_iter() .into_iter()
.flatten() .flatten()
.map(RemovedComponentEntity::into) .map(RemovedComponentEntity::into)
@ -211,7 +211,7 @@ impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> {
/// Like [`iter`](Self::iter), except also returning the [`EventId`] of the events. /// Like [`iter`](Self::iter), except also returning the [`EventId`] of the events.
pub fn iter_with_id(&mut self) -> RemovedIterWithId<'_> { pub fn iter_with_id(&mut self) -> RemovedIterWithId<'_> {
self.reader_mut_with_events() self.reader_mut_with_events()
.map(|(reader, events)| reader.iter_with_id(events)) .map(|(reader, events)| reader.read_with_id(events))
.into_iter() .into_iter()
.flatten() .flatten()
.map(map_id_events) .map(map_id_events)

View file

@ -895,7 +895,7 @@ pub mod common_conditions {
// calls of the run condition. Simply checking `is_empty` would not be enough. // calls of the run condition. Simply checking `is_empty` would not be enough.
// PERF: note that `count` is efficient (not actually looping/iterating), // PERF: note that `count` is efficient (not actually looping/iterating),
// due to Bevy having a specialized implementation for events. // due to Bevy having a specialized implementation for events.
move |mut reader: EventReader<T>| reader.iter().count() > 0 move |mut reader: EventReader<T>| reader.read().count() > 0
} }
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true` /// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`

View file

@ -136,7 +136,7 @@ pub(crate) fn play_gilrs_rumble(
.retain(|_gamepad, rumbles| !rumbles.is_empty()); .retain(|_gamepad, rumbles| !rumbles.is_empty());
// Add new effects. // Add new effects.
for rumble in requests.iter().cloned() { for rumble in requests.read().cloned() {
let gamepad = rumble.gamepad(); let gamepad = rumble.gamepad();
match handle_rumble_request(&mut running_rumbles, &mut gilrs, rumble, current_time) { match handle_rumble_request(&mut running_rumbles, &mut gilrs, rumble, current_time) {
Ok(()) => {} Ok(()) => {}

View file

@ -1023,7 +1023,7 @@ pub fn gamepad_connection_system(
mut button_axis: ResMut<Axis<GamepadButton>>, mut button_axis: ResMut<Axis<GamepadButton>>,
mut button_input: ResMut<Input<GamepadButton>>, mut button_input: ResMut<Input<GamepadButton>>,
) { ) {
for connection_event in connection_events.iter() { for connection_event in connection_events.read() {
let gamepad = connection_event.gamepad; let gamepad = connection_event.gamepad;
if let GamepadConnection::Connected(info) = &connection_event.connection { if let GamepadConnection::Connected(info) = &connection_event.connection {
@ -1168,7 +1168,7 @@ pub fn gamepad_axis_event_system(
mut gamepad_axis: ResMut<Axis<GamepadAxis>>, mut gamepad_axis: ResMut<Axis<GamepadAxis>>,
mut axis_events: EventReader<GamepadAxisChangedEvent>, mut axis_events: EventReader<GamepadAxisChangedEvent>,
) { ) {
for axis_event in axis_events.iter() { for axis_event in axis_events.read() {
let axis = GamepadAxis::new(axis_event.gamepad, axis_event.axis_type); let axis = GamepadAxis::new(axis_event.gamepad, axis_event.axis_type);
gamepad_axis.set(axis, axis_event.value); gamepad_axis.set(axis, axis_event.value);
} }
@ -1181,7 +1181,7 @@ pub fn gamepad_button_event_system(
mut button_input_events: EventWriter<GamepadButtonInput>, mut button_input_events: EventWriter<GamepadButtonInput>,
settings: Res<GamepadSettings>, settings: Res<GamepadSettings>,
) { ) {
for button_event in button_changed_events.iter() { for button_event in button_changed_events.read() {
let button = GamepadButton::new(button_event.gamepad, button_event.button_type); let button = GamepadButton::new(button_event.gamepad, button_event.button_type);
let value = button_event.value; let value = button_event.value;
let button_property = settings.get_button_settings(button); let button_property = settings.get_button_settings(button);
@ -1258,7 +1258,7 @@ pub fn gamepad_event_system(
mut button_input: ResMut<Input<GamepadButton>>, mut button_input: ResMut<Input<GamepadButton>>,
) { ) {
button_input.bypass_change_detection().clear(); button_input.bypass_change_detection().clear();
for gamepad_event in gamepad_events.iter() { for gamepad_event in gamepad_events.read() {
match gamepad_event { match gamepad_event {
GamepadEvent::Connection(connection_event) => { GamepadEvent::Connection(connection_event) => {
connection_events.send(connection_event.clone()); connection_events.send(connection_event.clone());

View file

@ -53,7 +53,7 @@ pub fn keyboard_input_system(
// Avoid clearing if it's not empty to ensure change detection is not triggered. // Avoid clearing if it's not empty to ensure change detection is not triggered.
scan_input.bypass_change_detection().clear(); scan_input.bypass_change_detection().clear();
key_input.bypass_change_detection().clear(); key_input.bypass_change_detection().clear();
for event in keyboard_input_events.iter() { for event in keyboard_input_events.read() {
let KeyboardInput { let KeyboardInput {
scan_code, state, .. scan_code, state, ..
} = event; } = event;

View file

@ -144,7 +144,7 @@ pub fn mouse_button_input_system(
mut mouse_button_input_events: EventReader<MouseButtonInput>, mut mouse_button_input_events: EventReader<MouseButtonInput>,
) { ) {
mouse_button_input.bypass_change_detection().clear(); mouse_button_input.bypass_change_detection().clear();
for event in mouse_button_input_events.iter() { for event in mouse_button_input_events.read() {
match event.state { match event.state {
ButtonState::Pressed => mouse_button_input.press(event.button), ButtonState::Pressed => mouse_button_input.press(event.button),
ButtonState::Released => mouse_button_input.release(event.button), ButtonState::Released => mouse_button_input.release(event.button),

View file

@ -366,7 +366,7 @@ pub fn touch_screen_input_system(
) { ) {
touch_state.update(); touch_state.update();
for event in touch_input_events.iter() { for event in touch_input_events.read() {
touch_state.process_touch_event(event); touch_state.process_touch_event(event);
} }
} }

View file

@ -608,7 +608,7 @@ pub fn extract_materials<M: Material>(
) { ) {
let mut changed_assets = HashSet::default(); let mut changed_assets = HashSet::default();
let mut removed = Vec::new(); let mut removed = Vec::new();
for event in events.iter() { for event in events.read() {
match event { match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {
changed_assets.insert(handle.clone_weak()); changed_assets.insert(handle.clone_weak());

View file

@ -575,11 +575,11 @@ pub fn camera_system<T: CameraProjection + Component>(
let primary_window = primary_window.iter().next(); let primary_window = primary_window.iter().next();
let mut changed_window_ids = HashSet::new(); let mut changed_window_ids = HashSet::new();
changed_window_ids.extend(window_created_events.iter().map(|event| event.window)); changed_window_ids.extend(window_created_events.read().map(|event| event.window));
changed_window_ids.extend(window_resized_events.iter().map(|event| event.window)); changed_window_ids.extend(window_resized_events.read().map(|event| event.window));
let changed_image_handles: HashSet<&Handle<Image>> = image_asset_events let changed_image_handles: HashSet<&Handle<Image>> = image_asset_events
.iter() .read()
.filter_map(|event| { .filter_map(|event| {
if let AssetEvent::Modified { handle } = event { if let AssetEvent::Modified { handle } = event {
Some(handle) Some(handle)

View file

@ -136,7 +136,7 @@ fn extract_render_asset<A: RenderAsset>(
) { ) {
let mut changed_assets = HashSet::default(); let mut changed_assets = HashSet::default();
let mut removed = Vec::new(); let mut removed = Vec::new();
for event in events.iter() { for event in events.read() {
match event { match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {
changed_assets.insert(handle.clone_weak()); changed_assets.insert(handle.clone_weak());

View file

@ -832,7 +832,7 @@ impl PipelineCache {
shaders: Extract<Res<Assets<Shader>>>, shaders: Extract<Res<Assets<Shader>>>,
mut events: Extract<EventReader<AssetEvent<Shader>>>, mut events: Extract<EventReader<AssetEvent<Shader>>>,
) { ) {
for event in events.iter() { for event in events.read() {
match event { match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {
if let Some(shader) = shaders.get(handle) { if let Some(shader) = shaders.get(handle) {

View file

@ -161,7 +161,7 @@ fn extract_windows(
} }
} }
for closed_window in closed.iter() { for closed_window in closed.read() {
extracted_windows.remove(&closed_window.window); extracted_windows.remove(&closed_window.window);
} }
// This lock will never block because `callbacks` is `pub(crate)` and this is the singular callsite where it's locked. // This lock will never block because `callbacks` is `pub(crate)` and this is the singular callsite where it's locked.

View file

@ -354,7 +354,7 @@ pub fn scene_spawner_system(world: &mut World) {
let scene_spawner = &mut *scene_spawner; let scene_spawner = &mut *scene_spawner;
for event in scene_spawner for event in scene_spawner
.scene_asset_event_reader .scene_asset_event_reader
.iter(scene_asset_events) .read(scene_asset_events)
{ {
if let AssetEvent::Modified { handle } = event { if let AssetEvent::Modified { handle } = event {
if scene_spawner.spawned_dynamic_scenes.contains_key(handle) { if scene_spawner.spawned_dynamic_scenes.contains_key(handle) {

View file

@ -467,7 +467,7 @@ pub fn extract_materials_2d<M: Material2d>(
) { ) {
let mut changed_assets = HashSet::default(); let mut changed_assets = HashSet::default();
let mut removed = Vec::new(); let mut removed = Vec::new();
for event in events.iter() { for event in events.read() {
match event { match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => { AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {
changed_assets.insert(handle.clone_weak()); changed_assets.insert(handle.clone_weak());

View file

@ -327,7 +327,7 @@ pub fn extract_sprite_events(
let SpriteAssetEvents { ref mut images } = *events; let SpriteAssetEvents { ref mut images } = *events;
images.clear(); images.clear();
for image in image_events.iter() { for image in image_events.read() {
// AssetEvent: !Clone // AssetEvent: !Clone
images.push(match image { images.push(match image {
AssetEvent::Created { handle } => AssetEvent::Created { AssetEvent::Created { handle } => AssetEvent::Created {

View file

@ -165,7 +165,7 @@ pub fn update_text2d_layout(
mut text_query: Query<(Entity, Ref<Text>, Ref<Text2dBounds>, &mut TextLayoutInfo)>, mut text_query: Query<(Entity, Ref<Text>, Ref<Text2dBounds>, &mut TextLayoutInfo)>,
) { ) {
// We need to consume the entire iterator, hence `last` // We need to consume the entire iterator, hence `last`
let factor_changed = scale_factor_changed.iter().last().is_some(); let factor_changed = scale_factor_changed.read().last().is_some();
// TODO: Support window-independent scaling: https://github.com/bevyengine/bevy/issues/5621 // TODO: Support window-independent scaling: https://github.com/bevyengine/bevy/issues/5621
let scale_factor = windows let scale_factor = windows

View file

@ -248,7 +248,7 @@ pub fn ui_layout_system(
}; };
let resized = resize_events let resized = resize_events
.iter() .read()
.any(|resized_window| resized_window.window == primary_window_entity); .any(|resized_window| resized_window.window == primary_window_entity);
// update window root nodes // update window root nodes

View file

@ -41,7 +41,7 @@ pub fn exit_on_primary_closed(
/// ///
/// [`WindowPlugin`]: crate::WindowPlugin /// [`WindowPlugin`]: crate::WindowPlugin
pub fn close_when_requested(mut commands: Commands, mut closed: EventReader<WindowCloseRequested>) { pub fn close_when_requested(mut commands: Commands, mut closed: EventReader<WindowCloseRequested>) {
for event in closed.iter() { for event in closed.read() {
commands.entity(event.window).despawn(); commands.entity(event.window).despawn();
} }
} }

View file

@ -46,7 +46,7 @@ fn handle_window_focus(
adapters: NonSend<AccessKitAdapters>, adapters: NonSend<AccessKitAdapters>,
mut focused: EventReader<WindowFocused>, mut focused: EventReader<WindowFocused>,
) { ) {
for event in focused.iter() { for event in focused.read() {
if let Some(adapter) = adapters.get(&event.window) { if let Some(adapter) = adapters.get(&event.window) {
adapter.update_if_active(|| { adapter.update_if_active(|| {
let focus_id = (*focus).unwrap_or_else(|| event.window); let focus_id = (*focus).unwrap_or_else(|| event.window);
@ -68,7 +68,7 @@ fn window_closed(
mut receivers: ResMut<WinitActionHandlers>, mut receivers: ResMut<WinitActionHandlers>,
mut events: EventReader<WindowClosed>, mut events: EventReader<WindowClosed>,
) { ) {
for WindowClosed { window, .. } in events.iter() { for WindowClosed { window, .. } in events.read() {
adapters.remove(window); adapters.remove(window);
receivers.remove(window); receivers.remove(window);
} }

View file

@ -356,7 +356,7 @@ pub fn winit_runner(mut app: App) {
} }
if let Some(app_exit_events) = app.world.get_resource::<Events<AppExit>>() { if let Some(app_exit_events) = app.world.get_resource::<Events<AppExit>>() {
if app_exit_event_reader.iter(app_exit_events).last().is_some() { if app_exit_event_reader.read(app_exit_events).last().is_some() {
*control_flow = ControlFlow::Exit; *control_flow = ControlFlow::Exit;
return; return;
} }
@ -723,14 +723,14 @@ pub fn winit_runner(mut app: App) {
if let Some(app_redraw_events) = if let Some(app_redraw_events) =
app.world.get_resource::<Events<RequestRedraw>>() app.world.get_resource::<Events<RequestRedraw>>()
{ {
if redraw_event_reader.iter(app_redraw_events).last().is_some() { if redraw_event_reader.read(app_redraw_events).last().is_some() {
runner_state.redraw_requested = true; runner_state.redraw_requested = true;
*control_flow = ControlFlow::Poll; *control_flow = ControlFlow::Poll;
} }
} }
if let Some(app_exit_events) = app.world.get_resource::<Events<AppExit>>() { if let Some(app_exit_events) = app.world.get_resource::<Events<AppExit>>() {
if app_exit_event_reader.iter(app_exit_events).last().is_some() { if app_exit_event_reader.read(app_exit_events).last().is_some() {
*control_flow = ControlFlow::Exit; *control_flow = ControlFlow::Exit;
} }
} }

View file

@ -277,7 +277,7 @@ fn camera_controller(
// Handle mouse input // Handle mouse input
let mut mouse_delta = Vec2::ZERO; let mut mouse_delta = Vec2::ZERO;
for mouse_event in mouse_events.iter() { for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta; mouse_delta += mouse_event.delta;
} }

View file

@ -291,7 +291,7 @@ pub fn camera_controller(
// Handle mouse input // Handle mouse input
let mut mouse_delta = Vec2::ZERO; let mut mouse_delta = Vec2::ZERO;
if mouse_button_input.pressed(options.mouse_key_enable_mouse) || *move_toggled { if mouse_button_input.pressed(options.mouse_key_enable_mouse) || *move_toggled {
for mouse_event in mouse_events.iter() { for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta; mouse_delta += mouse_event.delta;
} }
} }

View file

@ -95,7 +95,7 @@ fn set_camera_viewports(
// We need to dynamically resize the camera's viewports whenever the window size changes // We need to dynamically resize the camera's viewports whenever the window size changes
// so then each camera always takes up half the screen. // so then each camera always takes up half the screen.
// A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup. // A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
for resize_event in resize_events.iter() { for resize_event in resize_events.read() {
let window = windows.get(resize_event.window).unwrap(); let window = windows.get(resize_event.window).unwrap();
let mut left_camera = left_camera.single_mut(); let mut left_camera = left_camera.single_mut();
left_camera.viewport = Some(Viewport { left_camera.viewport = Some(Viewport {

View file

@ -307,7 +307,7 @@ fn update_image_viewer(
) { ) {
let mut new_image: Option<Handle<Image>> = None; let mut new_image: Option<Handle<Image>> = None;
for event in drop_events.iter() { for event in drop_events.read() {
match event { match event {
FileDragAndDrop::DroppedFile { path_buf, .. } => { FileDragAndDrop::DroppedFile { path_buf, .. } => {
new_image = Some(asset_server.load(path_buf.to_string_lossy().to_string())); new_image = Some(asset_server.load(path_buf.to_string_lossy().to_string()));
@ -328,7 +328,7 @@ fn update_image_viewer(
} }
} }
for event in image_events.iter() { for event in image_events.read() {
let image_changed_h = match event { let image_changed_h = match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => handle, AssetEvent::Created { handle } | AssetEvent::Modified { handle } => handle,
_ => continue, _ => continue,

View file

@ -10,7 +10,7 @@ fn main() {
} }
fn file_drag_and_drop_system(mut events: EventReader<FileDragAndDrop>) { fn file_drag_and_drop_system(mut events: EventReader<FileDragAndDrop>) {
for event in events.iter() { for event in events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
} }

View file

@ -57,7 +57,7 @@ fn spawn_text(mut commands: Commands, mut reader: EventReader<StreamEvent>) {
..default() ..default()
}; };
for (per_frame, event) in reader.iter().enumerate() { for (per_frame, event) in reader.read().enumerate() {
commands.spawn(Text2dBundle { commands.spawn(Text2dBundle {
text: Text::from_section(event.0.to_string(), text_style.clone()) text: Text::from_section(event.0.to_string(), text_style.clone())
.with_alignment(TextAlignment::Center), .with_alignment(TextAlignment::Center),

View file

@ -28,7 +28,7 @@ fn play_pitch(
mut events: EventReader<PlayPitch>, mut events: EventReader<PlayPitch>,
mut commands: Commands, mut commands: Commands,
) { ) {
for _ in events.iter() { for _ in events.read() {
info!("playing pitch with frequency: {}", frequency.0); info!("playing pitch with frequency: {}", frequency.0);
commands.spawn(PitchBundle { commands.spawn(PitchBundle {
source: pitch_assets.add(Pitch::new(frequency.0, Duration::new(1, 0))), source: pitch_assets.add(Pitch::new(frequency.0, Duration::new(1, 0))),

View file

@ -51,13 +51,13 @@ fn event_trigger(
// prints events as they come in // prints events as they come in
fn event_listener(mut events: EventReader<MyEvent>) { fn event_listener(mut events: EventReader<MyEvent>) {
for my_event in events.iter() { for my_event in events.read() {
info!("{}", my_event.message); info!("{}", my_event.message);
} }
} }
fn sound_player(mut play_sound_events: EventReader<PlaySound>) { fn sound_player(mut play_sound_events: EventReader<PlaySound>) {
for _ in play_sound_events.iter() { for _ in play_sound_events.read() {
info!("Playing a sound"); info!("Playing a sound");
} }
} }

View file

@ -11,7 +11,7 @@ fn main() {
/// This system prints out all char events as they come in /// This system prints out all char events as they come in
fn print_char_event_system(mut char_input_events: EventReader<ReceivedCharacter>) { fn print_char_event_system(mut char_input_events: EventReader<ReceivedCharacter>) {
for event in char_input_events.iter() { for event in char_input_events.read() {
info!("{:?}: '{}'", event, event.char); info!("{:?}: '{}'", event, event.char);
} }
} }

View file

@ -27,16 +27,16 @@ fn gamepad_events(
// this event is emmitted. // this event is emmitted.
mut button_input_events: EventReader<GamepadButtonInput>, mut button_input_events: EventReader<GamepadButtonInput>,
) { ) {
for connection_event in connection_events.iter() { for connection_event in connection_events.read() {
info!("{:?}", connection_event); info!("{:?}", connection_event);
} }
for axis_changed_event in axis_changed_events.iter() { for axis_changed_event in axis_changed_events.read() {
info!( info!(
"{:?} of {:?} is changed to {}", "{:?} of {:?} is changed to {}",
axis_changed_event.axis_type, axis_changed_event.gamepad, axis_changed_event.value axis_changed_event.axis_type, axis_changed_event.gamepad, axis_changed_event.value
); );
} }
for button_changed_event in button_changed_events.iter() { for button_changed_event in button_changed_events.read() {
info!( info!(
"{:?} of {:?} is changed to {}", "{:?} of {:?} is changed to {}",
button_changed_event.button_type, button_changed_event.button_type,
@ -44,7 +44,7 @@ fn gamepad_events(
button_changed_event.value button_changed_event.value
); );
} }
for button_input_event in button_input_events.iter() { for button_input_event in button_input_events.read() {
info!("{:?}", button_input_event); info!("{:?}", button_input_event);
} }
} }
@ -53,7 +53,7 @@ fn gamepad_events(
// stream directly. For standard use-cases, reading the events individually or using the // stream directly. For standard use-cases, reading the events individually or using the
// `Input<T>` or `Axis<T>` resources is preferable. // `Input<T>` or `Axis<T>` resources is preferable.
fn gamepad_ordered_events(mut gamepad_events: EventReader<GamepadEvent>) { fn gamepad_ordered_events(mut gamepad_events: EventReader<GamepadEvent>) {
for gamepad_event in gamepad_events.iter() { for gamepad_event in gamepad_events.read() {
match gamepad_event { match gamepad_event {
GamepadEvent::Connection(connection_event) => info!("{:?}", connection_event), GamepadEvent::Connection(connection_event) => info!("{:?}", connection_event),
GamepadEvent::Button(button_event) => info!("{:?}", button_event), GamepadEvent::Button(button_event) => info!("{:?}", button_event),

View file

@ -11,7 +11,7 @@ fn main() {
/// This system prints out all keyboard events as they come in /// This system prints out all keyboard events as they come in
fn print_keyboard_event_system(mut keyboard_input_events: EventReader<KeyboardInput>) { fn print_keyboard_event_system(mut keyboard_input_events: EventReader<KeyboardInput>) {
for event in keyboard_input_events.iter() { for event in keyboard_input_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
} }

View file

@ -24,29 +24,29 @@ fn print_mouse_events_system(
mut touchpad_magnify_events: EventReader<TouchpadMagnify>, mut touchpad_magnify_events: EventReader<TouchpadMagnify>,
mut touchpad_rotate_events: EventReader<TouchpadRotate>, mut touchpad_rotate_events: EventReader<TouchpadRotate>,
) { ) {
for event in mouse_button_input_events.iter() { for event in mouse_button_input_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
for event in mouse_motion_events.iter() { for event in mouse_motion_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
for event in cursor_moved_events.iter() { for event in cursor_moved_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
for event in mouse_wheel_events.iter() { for event in mouse_wheel_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
// This event will only fire on macOS // This event will only fire on macOS
for event in touchpad_magnify_events.iter() { for event in touchpad_magnify_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
// This event will only fire on macOS // This event will only fire on macOS
for event in touchpad_rotate_events.iter() { for event in touchpad_rotate_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
} }

View file

@ -142,7 +142,7 @@ fn listen_ime_events(
mut status_text: Query<&mut Text, With<Node>>, mut status_text: Query<&mut Text, With<Node>>,
mut edit_text: Query<&mut Text, (Without<Node>, Without<Bubble>)>, mut edit_text: Query<&mut Text, (Without<Node>, Without<Bubble>)>,
) { ) {
for event in events.iter() { for event in events.read() {
match event { match event {
Ime::Preedit { value, cursor, .. } if !cursor.is_none() => { Ime::Preedit { value, cursor, .. } if !cursor.is_none() => {
status_text.single_mut().sections[5].value = format!("IME buffer: {value}"); status_text.single_mut().sections[5].value = format!("IME buffer: {value}");
@ -168,7 +168,7 @@ fn listen_received_character_events(
mut events: EventReader<ReceivedCharacter>, mut events: EventReader<ReceivedCharacter>,
mut edit_text: Query<&mut Text, (Without<Node>, Without<Bubble>)>, mut edit_text: Query<&mut Text, (Without<Node>, Without<Bubble>)>,
) { ) {
for event in events.iter() { for event in events.read() {
edit_text.single_mut().sections[0].value.push(event.char); edit_text.single_mut().sections[0].value.push(event.char);
} }
} }
@ -178,7 +178,7 @@ fn listen_keyboard_input_events(
mut events: EventReader<KeyboardInput>, mut events: EventReader<KeyboardInput>,
mut edit_text: Query<(Entity, &mut Text), (Without<Node>, Without<Bubble>)>, mut edit_text: Query<(Entity, &mut Text), (Without<Node>, Without<Bubble>)>,
) { ) {
for event in events.iter() { for event in events.read() {
match event.key_code { match event.key_code {
Some(KeyCode::Return) => { Some(KeyCode::Return) => {
let (entity, text) = edit_text.single(); let (entity, text) = edit_text.single();

View file

@ -10,7 +10,7 @@ fn main() {
} }
fn touch_event_system(mut touch_events: EventReader<TouchInput>) { fn touch_event_system(mut touch_events: EventReader<TouchInput>) {
for event in touch_events.iter() { for event in touch_events.read() {
info!("{:?}", event); info!("{:?}", event);
} }
} }

View file

@ -31,7 +31,7 @@ fn touch_camera(
) { ) {
let window = windows.single(); let window = windows.single();
for touch in touches.iter() { for touch in touches.read() {
if touch.phase == TouchPhase::Started { if touch.phase == TouchPhase::Started {
*last_position = None; *last_position = None;
} }

View file

@ -466,7 +466,7 @@ fn update_button_values(
mut events: EventReader<GamepadButtonChangedEvent>, mut events: EventReader<GamepadButtonChangedEvent>,
mut query: Query<(&mut Text, &TextWithButtonValue)>, mut query: Query<(&mut Text, &TextWithButtonValue)>,
) { ) {
for button_event in events.iter() { for button_event in events.read() {
for (mut text, text_with_button_value) in query.iter_mut() { for (mut text, text_with_button_value) in query.iter_mut() {
if button_event.button_type == **text_with_button_value { if button_event.button_type == **text_with_button_value {
text.sections[0].value = format!("{:.3}", button_event.value); text.sections[0].value = format!("{:.3}", button_event.value);
@ -480,7 +480,7 @@ fn update_axes(
mut query: Query<(&mut Transform, &MoveWithAxes)>, mut query: Query<(&mut Transform, &MoveWithAxes)>,
mut text_query: Query<(&mut Text, &TextWithAxes)>, mut text_query: Query<(&mut Text, &TextWithAxes)>,
) { ) {
for axis_event in axis_events.iter() { for axis_event in axis_events.read() {
let axis_type = axis_event.axis_type; let axis_type = axis_event.axis_type;
let value = axis_event.value; let value = axis_event.value;
for (mut transform, move_with) in query.iter_mut() { for (mut transform, move_with) in query.iter_mut() {

View file

@ -174,7 +174,7 @@ fn camera_controller(
window.cursor.visible = false; window.cursor.visible = false;
} }
for mouse_event in mouse_events.iter() { for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta; mouse_delta += mouse_event.delta;
} }
} }

View file

@ -364,7 +364,7 @@ fn update_radio_buttons_colors(
mut text_query: Query<&mut Text>, mut text_query: Query<&mut Text>,
children_query: Query<&Children>, children_query: Query<&Children>,
) { ) {
for &ButtonActivatedEvent(button_id) in event_reader.iter() { for &ButtonActivatedEvent(button_id) in event_reader.read() {
let target_constraint = button_query.get_component::<Constraint>(button_id).unwrap(); let target_constraint = button_query.get_component::<Constraint>(button_id).unwrap();
for (id, constraint, interaction) in button_query.iter() { for (id, constraint, interaction) in button_query.iter() {
if target_constraint == constraint { if target_constraint == constraint {

View file

@ -316,7 +316,7 @@ fn mouse_scroll(
mut query_list: Query<(&mut ScrollingList, &mut Style, &Parent, &Node)>, mut query_list: Query<(&mut ScrollingList, &mut Style, &Parent, &Node)>,
query_node: Query<&Node>, query_node: Query<&Node>,
) { ) {
for mouse_wheel_event in mouse_wheel_events.iter() { for mouse_wheel_event in mouse_wheel_events.read() {
for (mut scrolling_list, mut style, parent, list_node) in &mut query_list { for (mut scrolling_list, mut style, parent, list_node) in &mut query_list {
let items_height = list_node.size().y; let items_height = list_node.size().y;
let container_height = query_node.get(parent.get()).unwrap().size().y; let container_height = query_node.get(parent.get()).unwrap().size().y;

View file

@ -86,7 +86,7 @@ fn on_resize_system(
mut resize_reader: EventReader<WindowResized>, mut resize_reader: EventReader<WindowResized>,
) { ) {
let mut text = q.single_mut(); let mut text = q.single_mut();
for e in resize_reader.iter() { for e in resize_reader.read() {
// When resolution is being changed // When resolution is being changed
text.sections[0].value = format!("{:.1} x {:.1}", e.width, e.height); text.sections[0].value = format!("{:.1} x {:.1}", e.width, e.height);
} }

View file

@ -13,7 +13,7 @@ struct EnemyDied(u32);
struct Score(u32); struct Score(u32);
fn update_score(mut dead_enemies: EventReader<EnemyDied>, mut score: ResMut<Score>) { fn update_score(mut dead_enemies: EventReader<EnemyDied>, mut score: ResMut<Score>) {
for value in dead_enemies.iter() { for value in dead_enemies.read() {
score.0 += value.0; score.0 += value.0;
} }
} }
@ -109,7 +109,7 @@ fn did_despawn_enemy() {
// Get `EnemyDied` event reader // Get `EnemyDied` event reader
let enemy_died_events = app.world.resource::<Events<EnemyDied>>(); let enemy_died_events = app.world.resource::<Events<EnemyDied>>();
let mut enemy_died_reader = enemy_died_events.get_reader(); let mut enemy_died_reader = enemy_died_events.get_reader();
let enemy_died = enemy_died_reader.iter(enemy_died_events).next().unwrap(); let enemy_died = enemy_died_reader.read(enemy_died_events).next().unwrap();
// Check the event has been sent // Check the event has been sent
assert_eq!(enemy_died.0, 1); assert_eq!(enemy_died.0, 1);