AsyncSystem
An AsyncSystem is a systematic combination of four Units, one each for every aspect of an asynchronous task or API, e.g.: XHR, fetch or a third party abstraction like Angular's HttpClient.
The four aspects of an async API are query, response, error, and pending-status. For each of these aspects, we have a Unit, wrapped inside the AsyncSystem.
AsyncSystem employs three GenericUnits for query, response, and error, namely queryUnit, dataUnit, and errorUnit, respectively; and a BoolUnit for the pending-status, named pendingUnit.
A BoolUnit is used for the pending-status because it can only be in two states, true or false
GenericUnit is used for the other three aspects because it's the most permissive of all the Units, and it saves us from creating multiple variations with different kinds of Units. However, you can substitute the GenericUnits with a different kind of Unit if you want and create your own custom AsyncSystem, very easily.
The below diagram shows where and how AsyncSystem helps with an asynchronous API call to the server, and how the data flow looks like, and how the AsyncSystem shares the API call's state with multiple parts of the App.
The data flow diagram of an async API call involving an AsyncSystem.
It might seem like a lot, but not everything is happening at the same time. When you break it down it's not difficult to understand.
  • The data flow starts with a dispatch to the queryUnit, which triggers an API call from the API Service.
  • The API Service contains the logic of listening to the queryUnit, making the actual API call, and then submitting its result back to the AsyncSystem, appropriately.
  • On a successful response, the API Service dispatches the response received, to the dataUnit.
  • On an error response, the API Service dispatches the error to the errorUnit.
  • The pendingUnit is updated automatically by the AsyncSystem, it's given a true value when queryUnit emits, and a false value when dataUnit or errorUnit emits a value.
That's pretty much it, this is how an AsyncSystem works.
There are other automatic things that an AsyncSystem can do apart from updating the value of pendingUnit. Such as, it can clear the errorUnit's value when dataUnit emits a value. It can freeze the queryUnit while the pendingUnit has a true value, etc.
See API reference for more details.
This is how the usage of AsyncSystem would look like in Angular and React apps.

Angular

user.state.ts
user.streams.ts
user.component.ts
user.component.html
user.module.ts
1
import {Injectable} from '@angular/core';
2
import {HttpErrorResponse} from '@angular/common/http';
3
import {AsyncSystem} from '@activejs/core';
4
​
5
@Injectable({providedIn: 'root'})
6
export class UserState {
7
​
8
// initialize an AsyncSystem and declare the typings such that
9
// query would be a number,
10
// data would be a string,
11
// error would be an HttpErrorResponse object
12
readonly userSystem = new AsyncSystem<number, string, HttpErrorResponse>();
13
14
// extract the Units for ease of access, or don't if you prefer
15
readonly userQuery = this.userSystem.queryUnit;
16
readonly userData = this.userSystem.dataUnit;
17
readonly userError = this.userSystem.errorUnit;
18
readonly userPending = this.userSystem.pendingUnit;
19
}
Copied!
1
import {Injectable} from '@angular/core';
2
import {HttpClient} from '@angular/common/http';
3
import {EMPTY, Observable} from 'rxjs';
4
import {catchError, switchMap, tap} from 'rxjs/operators';
5
import {UserState} from './user.state';
6
​
7
// Create a separate service for Streams, it helps avoid cyclic dependencies.
8
// It'll do all the heavy lifting, it'll make http requests and
9
// dispatch the results to the userDataSystem.
10
​
11
@Injectable() // we'll instantiate it in user.module.ts so no "provideIn"
12
export class UserStreams {
13
​
14
// create a Stream using the userSystem and couple it with an http request
15
userDataStream = this.userState.userSystem.createStream(
16
(
17
queryUnit, dataUnit, errorUnit
18
) => {
19
// listen to the future values of queryUnit
20
return queryUnit.future$.pipe(
21
// you can also do queryUnit.pipe, but that'll start immediately,
22
// without even dispatching anything to queryUnit
23
24
// switch the stream to http request Observable
25
// to create a new request
26
switchMap(userId => this.httpClient
27
.get('https://example.com/username' + userId)
28
.pipe(
29
// dispatch the returned data to dataUnit
30
tap(data => dataUnit.dispatch(data)),
31
32
// catch the error
33
catchError(err => {
34
35
// dispatch the error to errorUnit
36
errorUnit.dispatch(err);
37
38
// don't rethrow, to keep the stream alive
39
return EMPTY;
40
})
41
)
42
));
43
});
44
​
45
constructor(
46
private httpClient: HttpClient,
47
private userState: UserState
48
) {}
49
}
Copied!
1
import {Component} from '@angular/core';
2
import {UserState} from './user.state';
3
​
4
/*
5
An Angular component.
6
It will trigger the API request and show the response
7
along with loading-state.
8
*/
9
​
10
@Component({
11
selector: 'app-user',
12
templateUrl: 'user.component.html'
13
})
14
export class UserComponent {
15
userId: number;
16
​
17
constructor(public userState: UserState) {}
18
​
19
loadData() {
20
this.userState.userQuery.dispatch(this.userId);
21
}
22
​
23
reloadData() {
24
this.userState.userQuery.replay();
25
}
26
}
Copied!
1
<!-->
2
The template for Angular component.
3
</-->
4
​
5
<h1>Load data from a REST API using AsyncSystem.</h1>
6
​
7
<input type="number" [(ngModel)]="userId">
8
​
9
<button (click)="loadData()">Load Data</button>
10
<button (click)="reloadData()">Reload Data</button>
11
​
12
<p *ngIf="userState.userPending | async">
13
Loading...
14
</p>
15
​
16
<p *ngIf="userState.userData | async as name">
17
My name is: {{name}}
18
</p>
19
​
20
<p *ngIf="userState.userError | async as error">
21
Error: {{error.message}}
22
</p>
Copied!
1
import {NgModule} from '@angular/core';
2
import {CommonModule} from '@angular/common';
3
import {UserStreams} from './user.streams';
4
import {UserComponent} from './user.component';
5
​
6
// here we are creating a Feature Module, so we're making the UserStreams part of
7
// this module only, so they start working when this Module is used.
8
// But if we had more generic Streams-service we can do the same
9
// in the AppModule so that the Streams start when the app starts.
10
​
11
@NgModule({
12
declarations: [UserComponent],
13
imports: [CommonModule],
14
providers: [
15
// make the UserStreams part of dependecy injection
16
UserStreams,
17
// instantiate the UserStreams service using APP_INITILIZER, or
18
// we can do it in old fashioned way by putting in the contructor of AppModule
19
{
20
provide: APP_INITIALIZER,
21
useFactory: () => () => {},
22
deps: [UserStreams], // we can put as many Streams services here as we want
23
multi: true,
24
},
25
]
26
})
27
export class UserModule {}
Copied!
See this Typeahead example to for real-life usage.

React

This is how a typical usage would look like, using the React Hooks, and a custom Hook for using ActiveJS Units and Observables called useObservable.
user.state.ts
user.streams.ts
user.component.tsx
1
import {AsyncSystem} from '@activejs/core';
2
​
3
// initialize an AsyncSystem and declare the typings such that
4
// query would be a number,
5
// data would be a string,
6
// error would be an HttpErrorResponse object
7
export const userSystem = new AsyncSystem<string, string, any>();
8
​
9
// extract the Units for ease of access, or don't if you prefer
10
export const userQueryUnit = userSystem.queryUnit;
11
export const userDataUnit = userSystem.dataUnit;
12
export const userErrorUnit = userSystem.errorUnit;
13
export const userPendingUnit = userSystem.pendingUnit;
Copied!
1
// Create a separate file for Streams, it helps avoid cyclic dependencies.
2
// It'll do all the heavy lifting, it'll make http requests and
3
// dispatch the results to the userDataSystem.
4
​
5
import {EMPTY, Observable} from 'rxjs';
6
import {catchError, switchMap, tap} from 'rxjs/operators';
7
import {queryUnit, dataUnit, errorUnit} from './user.state';
8
​
9
// a function to fetch data and disptch the response appropriately
10
async function fetchAndShareData(query) {
11
try {
12
// fetch data using fetch API
13
const response = await fetch('https://xyz.com/u/' + query.userId);
14
// extract the JSON data
15
const data = await response.json();
16
​
17
// dispatch data to the dataUnit, it also sets the pendingUnit's value to false
18
// and it also clears the errorUnit's value
19
dataUnit.dispatch(data);
20
} catch (err) {
21
// dispatch error to errorUnit, it also sets the pendingUnit's value to false
22
errorUnit.dispatch(err);
23
}
24
}
25
​
26
// setup the stream by observing query values, that triggers fetchAndShareData
27
// whenever a value is dispatched to queryUnit
28
queryUnit.subscribe(query => fetchAndShareData(query));
Copied!
1
/*
2
A React component.
3
It will trigger the API request and show the response
4
along with loading-state.
5
*/
6
function App() {
7
const [userId, setUserId] = useState('');
8
9
const data = useObservable(userDataUnit);
10
const isPending = useObservable(userPendingUnit);
11
const error = useObservable(userErrorUnit);
12
​
13
const loadData = () => userQueryUnit.dispatch(userId);
14
const reloadData = () => userQueryUnit.replay();
15
​
16
return (
17
<React.Fragment>
18
<h1>Load data from a REST API using AsyncSystem.</h1>
19
{userId}
20
​
21
<input type="number" onChange={e => setUserId(e.target.value)}/>
22
​
23
{isPending && <p>Loading...</p>}
24
​
25
{data && <p>My name is: {data}</p>}
26
​
27
{error && <p>Error: {error}</p>}
28
​
29
<button onClick={loadData}>Load Data</button>
30
<button onClick={reloadData}>Reload</button>
31
</React.Fragment>
32
);
33
}
Copied!
See this Typeahead example to for real-life usage.

Configuration Options

The configuration options can be passed at the time of instantiation. All the configuration options are optional. Most of the options can also be set globally. See Configuration for more details.