← Asynchronous resources

Resource.new

luastra/resource
Resource.new(options: ReadOptions<T>): ReadState<T>

Creates a reusable controller for one asynchronously loaded value. Tickets and generations reject late completions, while snapshots distinguish initial load, refresh, retry, empty data, stale data with an error, cancellation, and invalidation.

Before you use it

Add luastra/resource to this module's dependencies in luastra.json, then import it with require("luastra/resource"). Create each controller once outside app.render. Record the exact ticket returned by begin, correlate it with the host RequestId, and settle only that ticket from app.resolve or another admitted completion boundary.

How it fits

Constructors and transitions are synchronous. begin creates a new generation ticket; resolve, reject, and cancel accept only the active ticket; snapshot returns the current frozen view used by render.

When to use it

Use Resource.new for profiles, settings, documents, or any other single logical value that may be loaded and refreshed. Store the returned controller outside render, start work from event logic, and render only from its immutable snapshot.

Parameters

ParameterType / valuesDescription
optionsReadOptions<T>Checked options argument accepted by Resource.new.

Returns

ReadState<T> — the exact ReadState<T> value declared by the SDK contract.

What happens next

A reusable read or mutation controller whose snapshot represents loading, success, empty, stale failure, retry, cancellation, or submission state.

Failures and fixes

Invalid options and programmer contract violations fail immediately. A stale ticket returns false without overwriting current state. Translate provider failures to bounded Resource.Error codes and keep raw messages, payloads, tokens, and credentials outside the controller.

Availability

Public-source alpha state API in 0.5.0-alpha; host-independent and designed to compose with any asynchronous capability.

Focused example

local Resource = require("luastra/resource")

local profile = Resource.new {
    isEmpty = function(value: { name: string }): boolean
        return value.name == ""
    end,
}

local ticket = profile.begin(requestId, "load")
if result ~= nil then
    profile.resolve(ticket, result)
else
    profile.reject(ticket, Resource.error("NOT_FOUND", false))
end

local snapshot = profile.snapshot()

Complete inventory

View all pages in Asynchronous resources
← Previous: Resource.errorNext: Resource.newMutation →