edifice.use_async_call#

edifice.use_async_call(fn_coroutine)[source]#

Hook to call an async function from a non-async context.

The async fn_coroutine function can have any argument signature, but it must return None. The return value is discarded.

The Hook takes an async function fn_coroutine and returns a tuple pair of non-async functions.

  1. A non-async function with the same argument signature as the fn_coroutine. When called, this non-async function will start a new Task an the main Edifice thread event loop as a use_async() Hook which calls fn_coroutine. This non-async function is safe to call from any thread.

  2. A non-async cancellation function which can be called to cancel the fn_coroutine Task manually. This cancellation function is safe to call from any thread.

use_async_call to delay print#
async def delay_print_async(message:str):
    await asyncio.sleep(1)
    print(message)

delay_print, cancel_print = use_async_call(delay_print_async)

delay_print("Hello World")

Some time later, if we want to manually cancel the delayed print:

cancel the delayed print#
cancel_print()

This Hook is similar to useAsyncCallback from https://www.npmjs.com/package/react-async-hook

This Hook is similar to create_task() , but because it uses use_async(), it will cancel the Task when this @component is unmounted, or when the function is called again.

Parameters:

fn_coroutine (Callable[[ParamSpec(_P_async)], Awaitable[None]]) – Async Coroutine function to be run as a Task.

Return type:

tuple[Callable[[ParamSpec(_P_async)], None], Callable[[], None]]

Returns:

A tuple pair of non-async functions.
  1. A non-async function with the same argument signature as the fn_coroutine.

  2. A non-async cancellation function which can be called to cancel the fn_coroutine Task manually.