/* Copyright 2025 New Vector Ltd. SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial Please see LICENSE in the repository root for full details. */ import { catchError, from, map, Observable, of, startWith, switchMap, } from "rxjs"; export type Async = | { state: "loading" } | { state: "error"; value: Error } | { state: "ready"; value: A }; export const loading: Async = { state: "loading" }; export function error(value: Error): Async { return { state: "error", value }; } export function ready(value: A): Async { return { state: "ready", value }; } export function async(promise: Promise): Observable> { return from(promise).pipe( map(ready), startWith(loading), catchError((e) => of(error(e))), ); } export function mapAsync( async: Async, project: (value: A) => B, ): Async { return async.state === "ready" ? ready(project(async.value)) : async; }