Same as evt.pipe(...) but return a StatefulEvt. Be aware that the current state of the StatefulEvt must be matched by the operator ( if any ) when invoking .pipe(), elst an exception will be thrown.
import { Evt } from"evt";// Evt that post whenever the window is resized window.addEventListener("resize", ...)constevtResize=Evt.from(window,"resize");// A statefulle evt with evtInnerWith state which is always the current value of// window.innerSize.constevtInnerWidth= evtResize.toStatefull() // convert into a statefull evt with initial value set to unefined.pipe(()=> [window.innerWidth]);
onlyIfChanged operator
When using stetefull Evt is often usefull to have event posted only when the state value has changed. For that purpose you can pipe with the onlyIfChanged operator.
Concrete example:
If we take the previous example:
import { Evt } from"evt";constevtInnerWidth=Evt.from(window,"resize").toStatefull() .pipe(()=> [window.innerWidth]);evtInnerWith.attach(innerWidth => {// This callback will be called whenever the screen is resized // including if only if the height has changed because// window.addEventListener("resize", ()=> ... // is the source event emitter. });
Now if we put the onlyIfChanged operator intor the mix:
import { Evt, onlyIfChanged } from"evt";constevtInnerWidth=Evt.from(window,"resize").toStatefull() .pipe(()=> [window.innerWidth])// By default it compare object structure so { foo: 3 } is considered equal to // an other object that would also be { foo: 3 }.pipe(onlyIfChanged());evtInnerWith.attach(innerWidth => {// This callback will only be called whenever window.innerWidth// actually changes. });
Merging multiple StatefulEvts
import { Evt } from"evt";constevtIsBlue=Evt.create(false);constevtIsBig=Evt.create(false);constevtIsBigAndBlue=Evt.merge([evtIsBlue.evtChange,evtIsBig.evtChange]).toStateful().pipe(()=> [ evtIsBlue.state &&evtIsBig.state ]) ;console.log(evtIsBigAndBlue.state); // Prints "false"evtIsBlue.state=true;console.log(evtIsBigAndBlue.state); // Prints "false"evtIsBig.state=true;console.log(evtIsBigAndBlue.state); // Prints "true"