Skip to content

resource API

Use resource(...) or @resource to connect asynchronous loading to a reactive parameter graph. Resources expose synchronous signal-like accessors for status, value, error, loading state, and snapshots.

Naming

Prefer resource(...) and @resource in application code. Resource is the concrete async resource class and remains supported for existing class-style code, type references, and advanced use.

reaktiv.resource

Resource - Async reactivity with resources.

A Resource gives you a way to incorporate async data into your application's signal-based code and still allow you to access its data synchronously.

This implementation is inspired by Angular's ResourceSignal.

PreviousResourceState dataclass

Container for previous resource state information.

Resource

Bases: Generic[P, T]

A reactive resource that handles async data loading.

Provides a signal-based interface for async operations with automatic dependency tracking, cancellation support, and status management.

IMPORTANT: Resource must be created within an async context (i.e., when an event loop is running). This ensures proper async task scheduling and prevents threading complexity.

cancellation_event property

Get the current cancellation event, if any.

Returns the cancellation event for the currently running request, or None if no request is in progress. The loader can check event.is_set() to see if the request was cancelled.

error property

Readonly signal containing the most recent error or None.

is_loading property

Readonly signal indicating whether the loader is currently running.

status property

Readonly signal containing the current status of the resource.

value property

Signal containing the loaded value or None if not yet loaded.

Reading this signal will throw if the resource is in error state. Use has_value() as a guard before reading this in computed signals.

__del__()

Automatic cleanup when garbage collected.

Cancels any pending async tasks when the Resource is garbage collected, preventing resource leaks.

__init__(params, loader=None)

__init__(params: Callable[[Any], Optional[P]]) -> None
__init__(params: Callable[[], Optional[P]], loader: Callable[[ResourceLoaderParams[P]], Awaitable[T]]) -> None

Initialize a Resource.

Parameters:

Name Type Description Default
params Callable[..., Optional[P]]

A reactive computation that produces parameter values

required
loader Optional[Callable[[ResourceLoaderParams[P]], Awaitable[T]]]

An async function that loads data based on params

None

Raises:

Type Description
RuntimeError

If no asyncio event loop is running

destroy()

Clean up the resource by cancelling any pending tasks.

This method should be called when the resource is no longer needed to ensure proper cleanup of async tasks.

has_value()

Check if the resource has a valid value (type guard).

Returns True if the resource has a value and is not in error state. This method can be used as a type guard in computed signals before accessing the value.

Example
@computed
def name():
    return (
        resource.value()["name"]
        if resource.has_value()
        else "Loading..."
    )

previous_status()

Get the previous status of the resource.

This is useful for tracking state transitions and implementing optimistic updates or caching strategies.

reload()

Manually trigger the loader to reload data.

This will execute the loader even if params haven't changed, and sets the status to RELOADING during the operation.

set(value)

Locally set the resource value.

This sets the status to LOCAL and cancels any ongoing load.

snapshot()

Get an atomic snapshot of the resource's current state.

Returns a computed signal containing a ResourceSnapshot with the current status, value (if available), and error (if any). This provides a way to access the resource's state atomically without multiple signal reads.

Example
def show_data():
    snap = resource.snapshot()()
    if snap.status == ResourceStatus.RESOLVED:
        print(f"Value: {snap.value}")
    elif snap.status == ResourceStatus.ERROR:
        print(f"Error: {snap.error}")

update(update_fn)

Update the resource value using a function.

This sets the status to LOCAL and cancels any ongoing load.

ResourceDescriptor

Bases: PerInstanceDescriptor['Resource[P, T]'], Generic[P, T]

Descriptor that creates one Resource per owner instance.

ResourceLoaderParams dataclass

Bases: Generic[P]

Parameters passed to a resource loader function.

ResourceSnapshot dataclass

Bases: Generic[T]

Atomic snapshot of a resource's current state.

Either contains a value (when resolved/loading/reloading/local) or an error.

ResourceStatus

Bases: str, Enum

Status of a resource's async operation.

Attributes:

Name Type Description
IDLE

No valid request and the loader has not run

ERROR

The loader has encountered an error

LOADING

The loader is running as a result of the params value changing

RELOADING

The loader is running as a result of reload() being called

RESOLVED

The loader has completed successfully

LOCAL

The resource's value has been set locally via set() or update()

reaktiv.Resource

A reactive resource that handles async data loading.

Provides a signal-based interface for async operations with automatic dependency tracking, cancellation support, and status management.

IMPORTANT: Resource must be created within an async context (i.e., when an event loop is running). This ensures proper async task scheduling and prevents threading complexity.

value property

Signal containing the loaded value or None if not yet loaded.

Reading this signal will throw if the resource is in error state. Use has_value() as a guard before reading this in computed signals.

error property

Readonly signal containing the most recent error or None.

is_loading property

Readonly signal indicating whether the loader is currently running.

status property

Readonly signal containing the current status of the resource.

cancellation_event property

Get the current cancellation event, if any.

Returns the cancellation event for the currently running request, or None if no request is in progress. The loader can check event.is_set() to see if the request was cancelled.

__init__(params, loader=None)

__init__(params: Callable[[Any], Optional[P]]) -> None
__init__(params: Callable[[], Optional[P]], loader: Callable[[ResourceLoaderParams[P]], Awaitable[T]]) -> None

Initialize a Resource.

Parameters:

Name Type Description Default
params Callable[..., Optional[P]]

A reactive computation that produces parameter values

required
loader Optional[Callable[[ResourceLoaderParams[P]], Awaitable[T]]]

An async function that loads data based on params

None

Raises:

Type Description
RuntimeError

If no asyncio event loop is running

reload()

Manually trigger the loader to reload data.

This will execute the loader even if params haven't changed, and sets the status to RELOADING during the operation.

previous_status()

Get the previous status of the resource.

This is useful for tracking state transitions and implementing optimistic updates or caching strategies.

snapshot()

Get an atomic snapshot of the resource's current state.

Returns a computed signal containing a ResourceSnapshot with the current status, value (if available), and error (if any). This provides a way to access the resource's state atomically without multiple signal reads.

Example
def show_data():
    snap = resource.snapshot()()
    if snap.status == ResourceStatus.RESOLVED:
        print(f"Value: {snap.value}")
    elif snap.status == ResourceStatus.ERROR:
        print(f"Error: {snap.error}")

has_value()

Check if the resource has a valid value (type guard).

Returns True if the resource has a value and is not in error state. This method can be used as a type guard in computed signals before accessing the value.

Example
@computed
def name():
    return (
        resource.value()["name"]
        if resource.has_value()
        else "Loading..."
    )

set(value)

Locally set the resource value.

This sets the status to LOCAL and cancels any ongoing load.

update(update_fn)

Update the resource value using a function.

This sets the status to LOCAL and cancels any ongoing load.

destroy()

Clean up the resource by cancelling any pending tasks.

This method should be called when the resource is no longer needed to ensure proper cleanup of async tasks.

__del__()

Automatic cleanup when garbage collected.

Cancels any pending async tasks when the Resource is garbage collected, preventing resource leaks.

reaktiv.ResourceStatus

Status of a resource's async operation.

Attributes:

Name Type Description
IDLE

No valid request and the loader has not run

ERROR

The loader has encountered an error

LOADING

The loader is running as a result of the params value changing

RELOADING

The loader is running as a result of reload() being called

RESOLVED

The loader has completed successfully

LOCAL

The resource's value has been set locally via set() or update()

reaktiv.ResourceLoaderParams dataclass

Parameters passed to a resource loader function.

reaktiv.ResourceSnapshot dataclass

Atomic snapshot of a resource's current state.

Either contains a value (when resolved/loading/reloading/local) or an error.