Skip to content

Instantly share code, notes, and snippets.

@baart1989
Created May 4, 2020 09:17
Show Gist options
  • Save baart1989/a8d75be7846fa6d6521ec7821b7a1810 to your computer and use it in GitHub Desktop.
Save baart1989/a8d75be7846fa6d6521ec7821b7a1810 to your computer and use it in GitHub Desktop.
Simple Angular - Redux connector
import { AnyAction, Store } from 'redux';
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { NgZone } from '@angular/core';
export type Comparator = (x: any, y: any) => boolean;
/**
* This interface represents the glue that connects the
* subscription-oriented Redux Store with the RXJS Observable-oriented
* Angular component world.
*
* Augments the basic Redux store interface with methods to
* enable selection
*/
@Injectable({ providedIn: 'root' })
export class ObservableStore<StateType> {
private reduxStore: Store<StateType> | undefined = undefined;
private state$: BehaviorSubject<StateType>;
constructor(private ngZone: NgZone, initialState: any) {
this.state$ = new BehaviorSubject(initialState);
}
provideStore(store: Store<StateType>) {
this.reduxStore = store;
this.reduxStore.subscribe(() => this.state$.next(this.reduxStore.getState()));
};
/**
* This method can be used to get some part of the redux state synchronously
*/
getState<SelectedType>(selector?: (state: StateType) => SelectedType): SelectedType {
return selector(this.reduxStore.getState());
}
/**
* This method can be used to get some part of the redux state asynchronously
*/
select<SelectedType>(selector?: (state: StateType) => SelectedType, comparator?: Comparator): Observable<SelectedType> {
return this.state$.asObservable().pipe(
distinctUntilChanged(),
map(state => selector(state)),
distinctUntilChanged(comparator)
);
}
dispatch<A extends AnyAction>(action: A) {
return NgZone.isInAngularZone() ?
this.reduxStore.dispatch(action) :
this.ngZone.run(() => this.reduxStore.dispatch(action));
};
subscribe(listener: () => void) {
return this.reduxStore.subscribe(listener);
}
}
@NayamAmarshe
Copy link

How do we use this, could you please share a brief snippet? @baart1989

@baart1989
Copy link
Author

baart1989 commented Nov 23, 2022

How do we use this, could you please share a brief snippet? @baart1989

Hope this helps - https://gist.github.com/baart1989/cd43036f233b747c202985a92bb2ef8e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment