Created
May 4, 2020 09:17
-
-
Save baart1989/a8d75be7846fa6d6521ec7821b7a1810 to your computer and use it in GitHub Desktop.
Simple Angular - Redux connector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hope this helps - https://gist.github.com/baart1989/cd43036f233b747c202985a92bb2ef8e