Operator<T, U> (type)
Operators provide a way to transform events data before they are passed to the callback.
EVT Operators can be of three types:
Filter:
(data: T)=> boolean
.Only the matched event data will be passed to the callback.
Type guard:
<U extends T>(data: T)=> data is U
Functionally equivalent to filter but restrict the event data type.
fλ
Filter / transform
Stateless fλ:
<U>(data: T)=> [U] | null
Map the input type T to an output type U.Stateful fλ:
[ <U>(data: T, prev: U)=> [U] | null, U /*initial value*/ ]
Same, but with a memory of the previous data.
Where to use operators
Operators functions can be used with:
All the
evt.attach*(...)
methods. They have to be prefixed with$
when used with fλ.The
evt.waitFor(...)
methodThe
evt.pipe(...)
method.
Operator - Filter
Let us consider the example use of an operator that filters out every word that does not start with 'H'.
It is important to be sure that your filter always return a boolean
, typewise you will be warned it is not the case but you must be sure that it is actually the case at runtime.
If in doubts use 'bang bang' ( !!returnedValue
). This note also applies for Type Gard operators.
Operator - Type guard
If you use a filter that is also a type guard, the type of the callback argument will be narrowed down to the matched type.
Let us define a straight forward type hierarchy to illustrate this feature.
The matchCircle
type guard can be used to attach a callback to an Evt<Shape>
that will only be called against circles.
Operator - fλ
Anonymous functions to simultaneously filter, transform the data and control the event flow.
fλ Returns
The type of values that a fλ operator sole determine what it does:
null
If the event should be ignored and nothing passed to the callback.[ U ]
When the event should be handled, wrapped into the singleton is the value will be passed to the callback.
Stateless fλ
Stateless fλ operator only takes the event data as arguments.
Stateful fλ
The result of the previously matched event is passed as argument to the operator.
****Run the example****
Side effect
If you want your operator to have side effect you should use the second argument of the operator function registerSideEffect
:
This is important becaue when you can the .isHandled() method on an evt the operator is invoked. Aditionally your operator can be invoked internally by Evt, it shouldn't produce side effect.
This is why it's important to make sure the the sideEffect is executed only when there is an actuall event posted.
Generic operators
Some generic operators are provided in "evt/operators"
such as scan
, throttleTime
or to
but that's about it.
Last updated