rx-data-store
From data source to reactive data store.
Demo
Check out demo here.
Introduction
You don't want to use NgRx for the state management of your application, but you are still looking for a lightweight solution.
Now, if you write the following code all the time, then this package is for you...
Let's say you have the following data source:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserApiService {
constructor(private httpClient: HttpClient) {}
get() {
return this.httpClient.get<User>('/api/user');
}
}
Here is the associated data store service and the component that consumes it:
import { map, ReplaySubject, tap } from 'rxjs';
import { Component, Injectable, OnInit } from '@angular/core';
@Injectable()
export class UserService {
private _user$ = new ReplaySubject<User>(1);
user$ = this._user$.asObservable();
constructor(private userApiService: UserApiService) {}
get() {
return this.userApiService.get().pipe(
tap((user) => this._user$.next(user)),
map(() => undefined)
);
}
}
@Component({
selector: 'app-root',
template: '<h1>Hello {{ (user$ | async)?.name }}</h1>',
})
export class AppComponent implements OnInit {
user$ = this.userService.user$;
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.get().subscribe();
}
}
Hmm... This is very verbose just to expose the user$
observable.
Now let's use RxDataStore
to simplify it all!
@Injectable()
export class UserService extends RxDataStore<User> {
constructor(private userApiService: UserApiService) {
super(() => this.userApiService.get());
}
}
@Component({
selector: 'app-root',
template: '<h1>Hello {{ (user$ | async)?.name }}</h1>',
})
export class AppComponent implements OnInit {
user$ = this.userService.data$;
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.fetch();
}
}
In this example, the UserService
inherits from RxDataStore
.
But, it's perfectly fine to use RxDataStore
as an instance property of the UserService
.
@Injectable()
export class UserService {
store = new RxDataStore<User>(() => this.userApiService.get());
constructor(private userApiService: UserApiService) {}
}
We're just scratching the surface here.
Let's dive into the features of RxDataStore
.
Usage
RxDataStore
integrates naturally with Angular since it is based on RxJS.
But since it only depends on RxJS, it can be used with any other framework.
API
The data source is a function that returns an observable.
Let's say this observable emits 2 consecutive values.
import { of } from 'rxjs';
const dataSource = (n: number) => of(n, n + 1).pipe(delay(0));
fetch data from data source
import { RxDataStore } from '@avine/rx-data-store';
const dataStore = new RxDataStore(dataSource);
dataStore.fetch(1);
dataStore.data$.subscribe((data) => console.log(data));
Note that the order does not matter.
You can subscribe to data$
even after the fetch
method has been called.
Set default arguments for data fetching
Calling the fetch
method is not necessary when the default arguments of the data source function are provided in the constructor.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
Note that even when the data source function has no arguments, you must set the default arguments to an empty array
(if you don't want to call the fetch
method).
new RxDataStore(dataSource, []);
setData
Replace data in the data store without fetching the data source.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
dataStore.setData(3);
updateData
Update the data in the data store based on the current state of the data.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
dataStore.updateData((data) => data + 1);
refresh
Refresh data from the data source using the latest arguments.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
dataStore.refresh();
mutation
Subscribe to an observable (the mutation) and update the data in the data store based on the current state of the data and the response of the mutation.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
dataStore.mutation(of(1), (data, response) => data + response).subscribe();
mutationQueue
Execute several mutations in order.
const dataStore = new RxDataStore(dataSource, [1]);
dataStore.data$.subscribe((data) => console.log(data));
dataStore.mutationQueue(of(1), (data, response) => data + response);
dataStore.mutationQueue(of(1), (data, response) => data + response);
pending$
The observable pending$
emits true
when a task is in progress and false
when it is idle.
dataStore.pending$.subscribe(console.log);
error$
The observable error$
emits errors that occur during task processing.
dataStore.error$.subscribe(console.log);
map
You can map the data emitted by the data$
observable.
This can be useful if, for example, you want to deeply clone the emitted data for immutability reasons.
import { cloneDeep } from 'lodash';
dataStore.map = cloneDeep;
RxDataStore.map = cloneDeep;
dataStore.map = 'noop';
useCache
Note that the latest data is always cached in the data store.
Enabling the cache is useful when the data source is called with different arguments.
const useCache = true;
const dataStore = new RxDataStore(dataSource, undefined, useCache);
dataStore.fetch(1);
dataStore.fetch(2);
dataStore.fetch(1);
clearCache
You can clear the cache at any time.
dataStore.clearCache();
License
MIT
Enjoy and have fun with RxDataStore
.