-
Notifications
You must be signed in to change notification settings - Fork 6
/
cross_system.rs
47 lines (41 loc) · 1.32 KB
/
cross_system.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! Cross system example - This example shows how to start a task from one system and poll it from
//! another through a resource.
use async_std::task::sleep;
use bevy::{app::PanicHandlerPlugin, log::LogPlugin, prelude::*, tasks::AsyncComputeTaskPool};
use bevy_async_task::{AsyncReceiver, AsyncTask, Duration};
#[derive(Resource, DerefMut, Deref, Default)]
struct MyTask(Option<AsyncReceiver<u32>>);
/// An async task that takes time to compute!
async fn long_task() -> u32 {
sleep(Duration::from_millis(1000)).await;
5
}
fn system1_start(mut my_task: ResMut<'_, MyTask>) {
let (fut, receiver) = AsyncTask::new(long_task()).build();
my_task.replace(receiver);
AsyncComputeTaskPool::get().spawn_local(fut).detach();
info!("Started!");
}
fn system2_poll(mut my_task: ResMut<'_, MyTask>) {
let Some(receiver) = my_task.0.as_mut() else {
return;
};
match receiver.try_recv() {
Some(Ok(v)) => {
info!("Received {v}");
}
None => {
// Waiting...
}
_ => unreachable!(),
}
}
/// Entry point
pub fn main() {
App::new()
.init_resource::<MyTask>()
.add_plugins((MinimalPlugins, LogPlugin::default(), PanicHandlerPlugin))
.add_systems(Startup, system1_start)
.add_systems(Update, system2_poll)
.run();
}