Actions are meant to represent unique reactive events. Action is an RxJS Subject like construct.
Actions don't replay the last value when subscribed to, unlike Units, Systems and Clusters.
Actions help trigger customized operations in a reactive fashion.
You can call an Action a simplified form of a Unit as they share the same base API, although configured in a slightly different way.
// access the valueconsole.log(multiplyAction.value()) // logs undefined// dynamically access the valuemultiplyAction.subscribe(value=>{console.log(value) // will log future values // do something with the value here});
Dispatching a value:
The above example shows the basic usage of an Action, it's similar to an RxJS Subject with slight differences.
Creating a stream:
The real-life usage would most probably be to create streams using the Action.
The advantage of using the createStream method is that we get a Stream instance.
So we can stop and re-start the multiplication stream.
Action vs Units vs BehaviorSubject
Action
Unit
BehaviorSubject
Replays value on subscription (by default)
β
β
β
Can be configured to replay value on subscription
β
β
β
Allows to listen to only future values
(useful when configured to replay on subscription)
The configuration options can be passed at the time of instantiation. All the configuration options are optional. Some options can also be set globally. See Configuration for more details.
// dispatch a value
multiplyAction.dispatch(3);
// replay the value
multiplyAction.replay(); // multiplyAction emits 3 again
// create a NumUnit to apply the multiplyAction on it
const numUnit = new NumUnit({initialValue: 10})
// create a stream using the earlier Action and above Unit
const subscription = multiplyAction.pipe(
tap(multiplier => {
// multiply the numUnit's value and update it
numUnit.dispatch(currValue => currValue * multiplier)
})
).subscribe();
// or simply use the built-in createStream method
const stream = multiplyAction.createStream(action$ => {
return action$.pipe(
tap(multiplier => {
// multiply the numUnit's value and update it
numUnit.dispatch(currValue => currValue * multiplier)
})
)
})
// stop the multiplication stream
stream.unsubscribe();
// re-start the multiplication stream
stream.resubscribe();