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. The same signal is returned on every access.

__del__()

Automatic cleanup when garbage collected.

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

__init__(params, loader=None, *, equal=None)

__init__(
    params: Callable[[Any], Optional[P]],
    *,
    equal: Optional[Callable[[Any, Any], bool]] = None,
) -> None
__init__(
    params: Callable[[], Optional[P]],
    loader: Callable[
        [ResourceLoaderParams[P]], Awaitable[T]
    ],
    *,
    equal: Optional[Callable[[T, T], bool]] = None,
) -> 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
equal Optional[Callable[[T, T], bool]]

Optional comparison for loaded/manual values; True retains the old value

None

Raises:

Type Description
RuntimeError

If no asyncio event loop is running

cancel()

Cancel the current load, retaining its last value and request dependencies.

Signals cancellation to the loader and cancels its asyncio task. Cleanup runs at the next await; even a loader that suppresses cancellation cannot publish its obsolete result. A parameter change or reload() starts a new load. Returns False when no load is running. Call on the resource's owner loop.

destroy()

Alias of :meth:dispose, kept for compatibility.

dispose()

Stop the resource permanently.

Cancels a running load (its result is never published), stops reacting to parameter changes, and turns reload() into a no-op. The last value, error and status stay readable. Call on the resource's event loop.

has_value()

Check if the resource has a valid value.

Returns True if the resource has a value and is not in error state. Check it before calling value(), which raises in the error state. It is a runtime check only: static type checkers do not narrow value() from Optional[T] to T after it.

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. The new value and status are published together. A rejected write (inside a computed or a Watcher notify callback) or a raising equal leaves the resource, including a running load, untouched.

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. Reading the current value here does not create a dependency.

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. Snapshots are immutable: the cached record is shared by every reader.

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()

CANCELLED

The current load was explicitly cancelled; any previous value is retained

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. The same signal is returned on every access.

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, *, equal=None)

__init__(
    params: Callable[[Any], Optional[P]],
    *,
    equal: Optional[Callable[[Any, Any], bool]] = None,
) -> None
__init__(
    params: Callable[[], Optional[P]],
    loader: Callable[
        [ResourceLoaderParams[P]], Awaitable[T]
    ],
    *,
    equal: Optional[Callable[[T, T], bool]] = None,
) -> 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
equal Optional[Callable[[T, T], bool]]

Optional comparison for loaded/manual values; True retains the old value

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.

Returns True if the resource has a value and is not in error state. Check it before calling value(), which raises in the error state. It is a runtime check only: static type checkers do not narrow value() from Optional[T] to T after it.

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. The new value and status are published together. A rejected write (inside a computed or a Watcher notify callback) or a raising equal leaves the resource, including a running load, untouched.

update(update_fn)

Update the resource value using a function.

This sets the status to LOCAL and cancels any ongoing load. Reading the current value here does not create a dependency.

cancel()

Cancel the current load, retaining its last value and request dependencies.

Signals cancellation to the loader and cancels its asyncio task. Cleanup runs at the next await; even a loader that suppresses cancellation cannot publish its obsolete result. A parameter change or reload() starts a new load. Returns False when no load is running. Call on the resource's owner loop.

dispose()

Stop the resource permanently.

Cancels a running load (its result is never published), stops reacting to parameter changes, and turns reload() into a no-op. The last value, error and status stay readable. Call on the resource's event loop.

destroy()

Alias of :meth:dispose, kept for compatibility.

__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()

CANCELLED

The current load was explicitly cancelled; any previous value is retained

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. Snapshots are immutable: the cached record is shared by every reader.

Value equality

resource(params=..., loader=..., equal=comparator) accepts a two-argument comparator for loaded and manually set values. Returning True retains the previous value and suppresses value updates; omitting the callback keeps identity comparison. resource[Params, Value](params, equal=comparator) also configures the descriptor. Loading/error status, cancellation, and request parameter comparison are independent of value equality.

Cancellation

resource.cancel() returns whether a load was running. It sets the loader's cancellation event, cancels its asyncio task, and sets status() to ResourceStatus.CANCELLED while retaining any previous value. A cancelled loader cannot publish a late result. Dependencies remain active; changing parameters or calling reload() starts a new load. Call cancellation on the resource's event loop. Async cleanup can run in finally; blocking work in native code or a separate thread still needs its own cancellation mechanism.

Disposal

resource.dispose() stops a resource permanently: it cancels a running load (whose result is never published), stops reacting to parameter changes, and makes reload() a no-op. The last value, error and status stay readable. Disposal is idempotent. destroy() is a compatibility alias of dispose().