0.6.4 • Published 8 months ago

rxo-state v0.6.4

Weekly downloads
-
License
-
Repository
github
Last release
8 months ago

RXO-STATE

Observable state management using RxJs.

Install

npm install rxo-state

Usage

Create a new state by extending RxoState abstract class

RxoState requires an initial state upon instantiation and an implementation for the mutate method.

export class MyState extends RxoState<{test: boolean}> {
    constructor() {
        super({test: true})
    }

    mutate(mutation:Mutation<boolean>): void {
        if(mutation.action === 'change') {
            this.next(mutation.data);
            this.emit("some-event", mutation.data);     // optional event emission
        }
        ...
    }
}

View current state value

const value = state.peek();

Observe changes to state

const subscription = state.observe().subscribe((value) => {
    console.log(value);
});

subscription.unsubscribe();   // unsubscribe from subscription

Mutate the state

state.mutate({
    action: "change",
    data: {
        test: true
    }
});

Listen for events emitted by mutators

state.listen("some-event", (value) => {
    console.log(value);
});

Emit an event from a mutator

Events can be emitted from the subclass of RxoState by call the emit method.

this.emit("some-event", mutation.data);

Reset the state to the initial value it was created with

The reset method will always emit the RXO_RESET event with the initial state as its value.

state.reset()

Listen for the RXO_RESET event

state.listen(RXO_RESET, (value) => {
    console.log(value);
});

Listen for a custom event

state.listen("some-event", (value) => {
    console.log(value);
});

Execute a function whenever state changes

const subscription = state.signal((value => {
    console.log(value);
}));

subscription.unsubscribe();   // unsubscribe from subscription

Update Angular signal on state change

@Component({
    selector: 'app-root',
    template: `{{mySignal()}}`,
    ...
})

export class AppComponent implements OnInit, OnDestroy {
    public mySignal: signal(0);
    private subscription: Subscription;

    constructor(private state: MyRxoState) {}

    ngOnInit() {
        this.subscription = this.state.signal(signal.set);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
0.6.4

8 months ago

0.6.3

9 months ago

0.6.2

9 months ago

0.6.1

9 months ago

0.6.0

9 months ago

0.5.1

9 months ago

0.5.0

9 months ago

0.4.10

9 months ago

0.4.9

9 months ago

0.4.8

9 months ago

0.4.7

9 months ago

0.4.6

9 months ago

0.4.5

9 months ago

0.4.4

9 months ago

0.4.3

9 months ago

0.4.1

9 months ago

0.4.0

9 months ago

0.3.1

9 months ago

0.3.0

9 months ago

0.2.0

9 months ago