State management with rxjs
npm install @hub-fx/coreReactive state management with RxJS.
1. Installation
1. Core concepts
1. Reactables
1. Hub and Stores
1. Effects
1. Scoped Effects
1. Flow & Containment
1. Examples
1. Basic Counter
1. Scoped Effects - Updating Todos
1. Connecting Multiple Hubs - Event Prices
1. API
1. Reactable
1. RxBuilder
1. RxConfig
1. Other Interfaces
1. Effect
1. ScopedEffects
1. Action
1. Reducer
1. Testing
1. Reactables
npm i @hub-fx/core
Prerequisite: Basic understanding of Redux and RxJS is helpful.
In this documentation the term stream will refer to an RxJS observable stream.
Reactables (prefixed with Rx) are objects that encapulate all the logic required for state management. They expose a state$ observable and actions methods. Applications can subscribe to state$ to receive state changes and call action methods to trigger them.
``javascript
import { RxCounter } from '@hub-fx/examples';
const counterReactable = RxCounter();
const { state$, actions: { increment, reset } } = counterReactable;
state$.subscribe(({ count }) => {
// Update the count when state changes.
document.getElementById('count').innerHTML = count;
});
// Bind click handlers
document.getElementById('increment').addEventListener('click', increment);
document.getElementById('reset').addEventListener('click', reset);
`
For a full example, see Basic Counter Example.
Reactables are composed of Hubs & Stores.
The Hub is responsible for dispatching actions to the store(s) registered to the hub. It is also responsible for handling side effects. The main stream that initiates all actions and effects is the dispatcher$

When initializing a hub we can declare effects. The hub can listen for various actions and perform side effects as needed. Stores that are registered to the hub will be listening to these effects as well the dispatcher$.

Scoped Effects are dynamically created streams scoped to a particular action & key combination when an action is dispatch.

Avoid tapping your streams. This prevents logic leaking from the stream(s).
- i.e do not tap stream A to trigger an action on stream B. Instead consider declaring stream A as a source for stream B so the dependency is explicit.

Basic counter example. Button clicks dispatch actions to increment or reset the counter.
Basic Counter | Design Diagram | Try it out on StackBlitz.
Choose your framework
:-------------------------:|:-------------------------:|:-------------------------:
|
| 


Updating statuses of todo items shows scoped effects in action. An 'update todo' stream is created for each todo during update. Pending async calls in their respective stream are cancelled if a new request comes in with RxJS switchMap operator.
Todo Status Updates | Design Diagram | Try it out on StackBlitz.
Choose your framework
:-------------------------:|:-------------------------:|:-------------------------:
|
| 


This examples shows two sets of hubs & stores. The first set is responsible for updating state of the user controls. The second set fetches prices based on input from the first set.
Event Prices | Design Diagram | Try it out on StackBlitz.
Choose your framework
:-------------------------:|:-------------------------:|:-------------------------:
|
| 


Reactables provide the API for applications and UI components to receive and trigger state updates.
`typescript
export interface Reactable
state$: Observable
actions?: S;
}
export interface ActionMap {
[key: string | number]: (payload?: unknown) => void;
}
`
| Property | Description |
| -------- | ----------- |
| state$ | Observable that emit state changes |
| actions (optional) | Dictionary of methods that dispatches actions to update state |
RxBuilder factory help build Reactables. Accepts a RxConfig configuration object
`typescript
type RxBuilder =
`
Configuration object for creating Reactables.
`typescript
interface RxConfig
initialState: T;
reducers: S;
store?: boolean;
debug?: boolean;
effects?: Effect
sources?: Observable
}
interface Cases
[key: string]: SingleActionReducer
| {
reducer: SingleActionReducer
effects?: (payload?: unknown) => ScopedEffects
};
}
type SingleActionReducer) => T;
`
| Property | Description |
| -------- | ----------- |
| initialState | Initial state of the Reactable |
| reducers | Dictionary of cases for the Reactable to handle. Each case can be a reducer function or a configuration object. RxBuilder will use this to generate Actions, Reducers, and add ScopedEffects. |
| debug (optional) | to turn on debugging to console.log all messages received by the store and state changes |
| store (optional) | Option to store value if Reactable is used to persist application state. Subsequent subscriptions will received the latest stored value. Default to false |
| effects (optional) | Array of Effects to be registered to the Reactable |
| sources (optional) | Additional Action Observables the Reactable is listening to |
Debug Example:

Effects are expressed as RxJS Operator Functions. They pipe the dispatcher$ stream and run side effects on incoming Actions.
`typescript`
type Effect>;
Scoped Effects are declared in Actions. They are dynamically created stream(s) scoped to an Action type & key combination.
`typescript`
interface ScopedEffects
key?: string;
effects: Effect
}type
| Property | Description |
| -------- | ----------- |
| key (optional) | key to be combined with the Action to generate a unique signature for the effect stream(s). Example: An id for the entity the action is being performed on. |type
| effects | Array of Effects scoped to the Action & key |
Example:
`typescript
const UPDATE_TODO = 'UPDATE_TODO';
const UPDATE_TODO_SUCCESS = 'UPDATE_TODO_SUCCESS';
const updateTodo = ({ id, message }, todoService: TodoService) => ({
type: UPDATE_TODO,
payload: { id, message },
scopedEffects: {
key: id,
effects: [
(updateTodoActions$: Observable
updateTodoActions$.pipe(
mergeMap(({ payload: { id, message } }) => todoService.updateTodo(id, message))
map(({ data }) => ({
type: UPDATE_TODO_SUCCESS,
payload: data
}))
)
]
}
})
`
#### Action
`typescript`
interface Action
type: string;
payload?: T;
scopedEffects?: ScopedEffects
}
| Property | Description |
| -------- | ----------- |
| type | type of Action being dispatched |
| payload (optional) | payload associated with Action |
| scopedEffects (optional) | See ScopedEffects |
From Redux Docs
> Reducers are functions that take the current state and an action as arguments, and return a new state result
`typescript`
type Reducer
We can use RxJS's built in Marble Testing for testing Reactables.
`typescript
// https://github.com/hub-fx/hub-fx/blob/main/packages/examples/src/Counter/Counter.test.ts
import { Counter } from './Counter';
import { Subscription } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
describe('Counter', () => {
let testScheduler: TestScheduler;
let subscription: Subscription;
beforeEach(() => {
testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
afterEach(() => {
subscription?.unsubscribe();
});
it('should increment and reset', () => {
testScheduler.run(({ expectObservable, cold }) => {
// Create Counter Reactable
const {
state$,
actions: { increment, reset },
} = Counter();
// Call actions
subscription = cold('--b-c', {
b: increment,
c: reset,
}).subscribe((action) => action());
// Assertions
expectObservable(state$).toBe('a-b-c', {
a: { count: 0 },
b: { count: 1 },
c: { count: 0 },
});
});
});
});
``