0.0.7 • Published 2 years ago

@appstrophe/ngx-computeasync v0.0.7

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

ngx-computeasync

Computed for async functions

Installation

Using npm:

npm i @appstrophe/ngx-computeasync

Using yarn:

yarn add @appstrophe/ngx-computeasync

Usage

import { Component, inject, signal } from '@angular/core'
import { computedAsync } from '@appstrophe/ngx-computeasync'

@Component({
  selector: 'app-test',
  template: `<p>{{ product() }}</p>`
})
export class TestComponent {
  productService = inject(ProductService);
  productId = signal(1);

  product = computedAsync(() => this.productService.getAsyncProduct(this.productId()));
}

computedAsync allows you to get a computed Signal from async content.

The content can either return a Promise and rxjs Observable or a synchronous value.

import { computedAsync } from '@appstrophe/ngx-computeasync'

numberSignal = signal(1);

// from Observable
function double$ = (value: number) => of(value).pipe(delay(500), map(value => value * 2));
computedFromObservable = computedAsync(() => double$(this.numberSignal()));

// from Promise
function asyncDouble = (value: number) => new Promise(resolve => setTimeout(() => value * 2, 500));
computedFromPromise = computedAsync(() => asyncDouble(this.numberSignal()));

// or synchronous
function double = (value: number) => value * 2;
computedNumber = computedAsync(() => double(this.numberSignal()));

Initial value

For async function, you can set a default value that will be immediately returned before the async value to be pushed.

import { computedAsync } from '@appstrophe/ngx-computeasync'

productId = signal(1);

function product$ = (productId: number) => this.http.get<Config>(`productUrl/${productId}`);

computedFromObservable = computedAsync(() => product$(this.productId()),
{ initialValue: new Product() });

Evaluation State

You will need to pass a WritableSignal or a BehaviorSubject to track if the async function is evaluating.

import { computedAsync } from '@appstrophe/ngx-computeasync'

evaluating = signal(false);

evaluatingEffect = effect(() => console.log(`Get product server call completed: ${this.evaluating()}`))

productId = signal(1);

function product$ = (productId: number) => this.http.get<Config>(`productUrl/${productId}`);

computedFromObservable = computedAsync(() => product$(this.productId()),
{ evaluating });

Playground

Stackblitz playground

0.0.7

2 years ago

0.0.6

2 years ago

0.0.3

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago