lol_game_client_api/
lib.rs

1use crate::api::GameClient;
2use crate::event_listener::EventListener;
3use std::error::Error;
4use std::time::Duration;
5
6pub mod api;
7pub mod event_listener;
8pub mod model;
9
10pub extern crate async_trait; // Re-export async_trait
11
12/// Take an event listener, and start a tasks that will periodically list all new events, and
13/// pass them to the listener callbacks.
14///
15/// This default implementation is fairly naive, and may quickly be obsolete.
16/// Not only does it require a strong bound on the Error type, but it also has poor performances.
17/// This waits for an event to be fully processed before processing another one. If a processing take some time,
18/// the processing of future events will be strongly delayed, which is suboptimal.
19pub fn start_listener<L: EventListener + 'static>(mut listener: L, period: Duration) {
20    tokio::spawn(async move {
21        let client = GameClient::new();
22
23        let mut previous_number_of_events = match client.event_data().await {
24            Ok(events) => {
25                log::info!("Running the program when the game is already started. {} events already happened.", events.events.len());
26                events.events.len()
27            }
28            Err(_) => {
29                log::info!("Game is not running yet");
30                0
31            }
32        };
33
34        loop {
35            let events = match client.event_data().await {
36                Ok(events) => events.events,
37                Err(err) => {
38                    log::error!("Failed to get event data: {}", err);
39                    tokio::time::sleep(period).await;
40                    continue;
41                }
42            };
43
44            let number_of_events = events.len();
45
46            if number_of_events <= previous_number_of_events {
47                // Nothing new...
48                log::debug!("Nothing new, still {} events", number_of_events);
49                tokio::time::sleep(period).await;
50                continue;
51            }
52
53            for event in events.as_slice()[previous_number_of_events..]
54                .to_vec()
55                .into_iter()
56            {
57                match listener.on_event(event).await {
58                    Ok(_) => {}
59                    Err(err) => listener.on_error(err).await,
60                };
61            }
62
63            previous_number_of_events = number_of_events;
64            tokio::time::sleep(period).await;
65        }
66    });
67}