use_task
A hook that runs a function or coroutine function as a task and returns the result.
def use_task(
f: Union[None, Callable[P, R]] = None,
*,
dependencies: Union[None, List] = [],
raise_error=True,
prefer_threaded=True,
) -> Union[Callable[[Callable[P, R]], Task[P, R]], Task[P, R]]:
...
Allows you to run code in the background, with the UI available to the user. This is useful for long running tasks, like downloading data or processing data.
Unlike with the @task
decorator, the result is not globally shared, but only available to the component that called use_task
.
Note that unlike the @task
decorator, the task is invoked immediately when dependencies are passed.
Example
Running in a thread
import time
import solara
from solara.lab import use_task, Task
@solara.component
def Page():
number = solara.use_reactive(4)
def square():
time.sleep(1)
return number.value**2
result: Task[int] = use_task(square, dependencies=[number.value])
solara.InputInt("Square", value=number, continuous_update=True)
if result.finished:
solara.Success(f"Square of {number} == {result.value}")
solara.ProgressLinear(result.pending)
Square of 4 == 16
Running in an asyncio task
Note that the only difference is our function is now a coroutine function,
and we use asyncio.sleep
instead of time.sleep
.
import asyncio
import solara
from solara.lab import use_task, Task
@solara.component
def Page():
number = solara.use_reactive(4)
async def square():
await asyncio.sleep(1)
return number.value**2
result: Task[int] = use_task(square, dependencies=[number.value])
solara.InputInt("Square", value=number, continuous_update=True)
if result.finished:
solara.Success(f"Square of {number} == {result.value}")
solara.ProgressLinear(result.pending)
Arguments
f
: The function or coroutine to run as a task.dependencies
: A list of dependencies that will trigger a rerun of the task when changed.raise_error
: If true, an error in the task will be raised. If false, the error should be handled by the user and is available in the.exception
attribute of the task result object.prefer_threaded
- bool: Will run coroutine functions as a task in a thread when threads are available. This ensures that even when a coroutine functions calls a blocking function the UI is still responsive. On platform where threads are not supported (like Pyodide / WASM / Emscripten / PyScript), a coroutine function will always run in the current event loop.