rxjs-state
RxState is a light-weight reactive state management service especially useful for component state in SPAs.
Description
RxState is a light-weight reactive state management service which is especially useful to organize component state.
install
npm install --save rxjs-state
Setup
As the RxState class is just a plain vanilla Javascript Class
; ;
API
setState
Add new slices to the state by providing an object
;state.setState;// new state => { foo: 'boo' } state.setState;// new state => { foo: 'boo', bar: 2 }
Add new Slices to the state by providing a projection function
; state.setState;state.setState;// new state => {bar: 3}
connect
Connect is one of the really cool thingy of this service.
It helps to write the output of an Observable
to the state and
handles subscription as well as unsubscription.
Connect to a single property
To understand that lets take a look at a normal implementation first:
; ;;subscription.unsubscribe;
Now lets compare that example with the connect usage:
state.connect'bar', newBar$;// the property bar will get values 1, 2, 3, 4, 5
Connect multiple properties
; ;state.connectslice$;// new state => { foo: 'foo', bar: 5}
select
Selecting state and extend the selection behavior with RxJS operators.
Other state management libs provide selector functions like react. The downside is they are not compossable.
RxState
provides state selection fully reactive.
State is lazy!
State is lazy! If nothing is set yet, nothing will emit. This comes in especially handy for lazy view rendering!
; ;bar$.subscribeconsole.log;// Never emits
Selecting the full state
; ;bar$.subscribeconsole.log;// Does not emitstate.setState;// emits { foo: 'boo'} for all old ane new subscriber
Access a single property
;state.setState; ;bar$.subscribeconsole.log; // 3
Access a nested property
;state.setState; ;boo$.subscribeconsole.log; // '42'
Access by providing rxjs operators
;state.setState;
hold
Managing side effects is core of every application.
The hold
method takes care of handling them.
It helps to handles subscription as well as unsubscription od side-effects
Hold a local observable side-effect
To understand that lets take a look at a normal implementation first:
;;subscription.unsubscribe;
If you would hold to achieve the same thing it would look like this:
state.holdsideEffect$;
Connect an observable trigger and provide an project function
;state.holdbtnClick$, console.logclickEvent;