minimal/
minimal.rs

1use std::time::Duration;
2
3use bevy::{log::LogPlugin, prelude::*, time::common_conditions::on_timer};
4use bevy_mod_reqwest::*;
5
6#[derive(Default, Resource)]
7// just a vector that stores all the responses as strings to showcase that the `on_response` methods
8// are just regular observersystems, that function very much like regular systems
9struct History {
10    pub responses: Vec<String>,
11}
12
13fn send_requests(mut client: BevyReqwest) {
14    let url = "https://bored-api.appbrewery.com/random";
15
16    // use regular reqwest http calls, then poll them to completion.
17    let reqwest_request = client.get(url).build().unwrap();
18
19    client
20        // Sends the created http request
21        .send(reqwest_request)
22        // The response from the http request can be reached using an observersystem,
23        // where the only requirement is that the first parameter in the system is the specific Trigger type
24        // the rest is the same as a regular system
25        .on_response(
26            |trigger: On<ReqwestResponseEvent>, mut history: ResMut<History>| {
27                let response = trigger.event();
28                let data = response.as_str();
29                let status = response.status();
30                // let headers = req.response_headers();
31                bevy::log::info!("code: {status}, data: {data:?}");
32                if let Ok(data) = data {
33                    history.responses.push(format!("OK: {data}"));
34                }
35            },
36        )
37        // In case of request error, it can be reached using an observersystem as well
38        .on_error(
39            |trigger: On<ReqwestErrorEvent>, mut history: ResMut<History>| {
40                let e = &trigger.event().entity;
41                bevy::log::info!("error: {e:?}");
42                history.responses.push(format!("ERROR: {e:?}"));
43            },
44        );
45}
46
47fn main() {
48    App::new()
49        .add_plugins(MinimalPlugins)
50        .add_plugins(LogPlugin::default())
51        .add_plugins(ReqwestPlugin::default())
52        .init_resource::<History>()
53        .add_systems(
54            Update,
55            send_requests.run_if(on_timer(Duration::from_secs(5))),
56        )
57        .run();
58}