Coder Social home page Coder Social logo

austinhellerrepo / bevy-async-task Goto Github PK

View Code? Open in Web Editor NEW

This project forked from loopystudios/bevy_async_task

0.0 0.0 0.0 67 KB

Ergonomic abstractions to async programming in Bevy for all platforms.

Home Page: https://crates.io/crates/bevy-async-task

License: Apache License 2.0

Rust 100.00%

bevy-async-task's Introduction

Bevy Async Task

MIT/Apache 2.0 crates.io docs.rs

A minimum crate for ergonomic abstractions to async programming in Bevy for all platforms. This crate helps to run async tasks in the background with timeout support and retrieve results in the same system, and helps to block on futures within synchronous contexts.

There is full API support for wasm and native. Android and iOS are untested (Help needed).

Bevy version support

bevy bevy-async-task
0.12 1.3, main
0.11 1.2
<= 0.10 Unsupported

Usage

Please see examples for more.

Polling in systems

Poll one task at a time with AsyncTaskRunner<T>:

async fn long_task() -> u32 {
    sleep(Duration::from_millis(1000)).await;
    5
}

fn my_system(mut task_executor: AsyncTaskRunner<u32>) {
    match task_executor.poll() {
        AsnycTaskStatus::Idle => {
            task_executor.begin(long_task());
            println!("Started new task!");
        }
        AsnycTaskStatus::Pending => {
            // <Insert loading screen>
        }
        AsnycTaskStatus::Finished(v) => {
            println!("Received {v}");
        }
    }
}

Poll many similar tasks simultaneously with AsyncTaskPool<T>:

fn my_system(mut task_pool: AsyncTaskPool<u64>) {
    if task_pool.is_idle() {
        println!("Queueing 5 tasks...");
        for i in 1..=5 {
            task_pool.spawn(async move { // Closures work too!
                sleep(Duration::from_millis(i * 1000)).await;
                i
            });
        }
    }

    for status in task_pool.iter_poll() {
        if let AsyncTaskStatus::Finished(t) = status {
            println!("Received {t}");
        }
    }
}

Also, you may use timeouts or block on an AsyncTask<T>:

// Blocking:
let task = AsyncTask::new(async { 5 });
assert_eq!(5, task.blocking_recv());

// Timeout:
let task = AsyncTask::<()>::pending().with_timeout(Duration::from_millis(10));
assert!(task.blocking_recv().is_err());

Need to steer manually? Break the task into parts.

let task = AsyncTask::new(async move {
    sleep(Duration::from_millis(1000)).await;
    5
});
// Break the task into a runnable future and a receiver
let (fut, mut rx) = task.into_parts();
// The receiver will always be `None` until it is polled by Bevy.
assert_eq!(None, rx.try_recv());
// Run the future
let task_pool = bevy::prelude::AsyncComputeTaskPool::get();
let task = task_pool.spawn(fut);
task.detach(); // Forget and run in background
// Spin-lock, waiting for the result
let result = loop {
    if let Some(v) = rx.try_recv() {
        break v;
    }
};
assert_eq!(5, result);

License

This project is dual-licensed under both Apache 2.0 and MIT licenses.

bevy-async-task's People

Contributors

simbleau avatar austinhellerrepo avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.