Fix(examples): improve async examples to showcase good patterns#21647
Conversation
|
Both of these examples look good to me, using check_ready instead of block_on is just correct. The channel example looks good, I would actually like to see an example of bi-directional communication from ecs <-> the async task, but that's just in general something that I think would be good to add as another more complex example of how you can use channels ( I find people get confused about the idea that you need to have senders and receivers on both ends in order to do bi-directional communication ). I think in no way that should block this from being merged, just something else you could PR! |
implement review feedback Co-authored-by: François Mockers <francois.mockers@vleue.com>
|
Your PR caused a change in the graphical output of an example or rendering test. This might be intentional, but it could also mean that something broke! If it's expected, please add the M-Deliberate-Rendering-Change label. If this change seems unrelated to your PR, you can consider updating your PR to target the latest main branch, either by rebasing or merging main into it. |
Thanks @MalekiRe for your feedback and the suggestion! That’s a really good idea. I’ll take a look into possible ways to create a meaningful bi-directional example. |
Objective
In #21598 and the related Discord discussion, it was pointed out that the
async_computeexample promotes an inefficient and potentially error-prone pattern:future::block_on(poll_once).It is now recommended to use
bevy::tasks::futures::check_readyinstead, which is much cheaper and avoids blocking the main thread while waiting on the future. Another valid approach is to pass a channel into the async tasks and detach them, letting the channel handle task readiness.This PR implements both suggestions.
Solution
Updated
async_computeexampleReplaced the use of
future::block_on(poll_once)with the recommendedcheck_ready.The change is minimal and limited to the directly affected lines.
Added new example:
async_channel_patternDemonstrates how to spawn async tasks using a channel-based communication pattern.
AsyncComputeTaskPool.CubeChannelonce completed.I am relatively new to both Bevy and async Rust, and I genuinely appreciate any feedback or suggestions to improve these examples — especially regarding idiomatic async patterns and best practices for Bevy task management.
Fixes #21598