async fn and async blocks are planned to compile to state machines, as in Rust. When a mod awaits a host operation, such as reading an asset, the mod is suspended and the game’s executor does the work. By default that’s bevy_tasks, and a tokio adapter is planned.
Network access needs the net capability. A mod gets no capabilities unless the game grants them.
commands.spawn_task runs an async block in the background.
10_async.ox
// async/await. Futures compile to state machines; awaiting a host operation
// suspends the mod while the host's executor (bevy_tasks) does the work.
use oxeon::assets::AssetReader;
use oxeon::net::Http;
#[derive(Debug)]
struct Quest {
id: u32,
title: String,
}
async fn load_quest(reader: &AssetReader, id: u32) -> Result<Quest, LoadError> {
let bytes = reader.read(format!("quests/{id}.json")).await?;
let quest = parse_quest(&bytes)?;
Ok(quest)
}
async fn load_all(reader: &AssetReader, ids: &[u32]) -> Vec<Quest> {
let mut quests = Vec::new();
for &id in ids {
if let Ok(q) = load_quest(reader, id).await {
quests.push(q);
}
}
quests
}
// Network access requires the `net` capability granted by the game.
async fn fetch_motd(http: &Http) -> Option<String> {
let response = http.get("https://example.com/motd").await.ok()?;
response.text().await.ok()
}
// Async blocks and spawning a background task.
fn start_loading(commands: &mut Commands, reader: AssetReader) {
let task = async move {
let quests = load_all(&reader, &[1, 2, 3]).await;
quests.len()
};
commands.spawn_task(task);
}