linera_base/
task.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Abstractions over tasks that can be used natively or on the Web.
6 */
7
8use futures::{future, Future, FutureExt as _};
9
10/// The type of a future awaiting another task.
11pub type NonBlockingFuture<R> = future::RemoteHandle<R>;
12
13/// Spawns a new task, potentially on the current thread.
14#[cfg(not(web))]
15pub fn spawn<F: Future<Output: Send> + Send + 'static>(future: F) -> NonBlockingFuture<F::Output> {
16    let (future, remote_handle) = future.remote_handle();
17    tokio::task::spawn(future);
18    remote_handle
19}
20
21/// Spawns a new task on the current thread.
22#[cfg(web)]
23pub fn spawn<F: Future + 'static>(future: F) -> NonBlockingFuture<F::Output> {
24    let (future, remote_handle) = future.remote_handle();
25    wasm_bindgen_futures::spawn_local(future);
26    remote_handle
27}