Skip to content

Instantly share code, notes, and snippets.

@ovrmrw
Last active December 29, 2016 16:31
Show Gist options
  • Save ovrmrw/9f6da803ef2c99fc412ea6e8e499b0c6 to your computer and use it in GitHub Desktop.
Save ovrmrw/9f6da803ef2c99fc412ea6e8e499b0c6 to your computer and use it in GitHub Desktop.
Simple concept for easy Redux
import 'core-js';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
type Action = {
key: string;
value: any;
}
type State = {
x: number;
y: string;
z: boolean;
}
const initialState: State = {
x: 1,
y: 'a',
z: true,
};
const simpleStore = new Subject<Action>();
const provider = new BehaviorSubject<State>(initialState);
const queue =
simpleStore
.concatMap(action => {
if (action.value instanceof Promise || action.value instanceof Observable) {
return Observable.from(action.value).mergeMap(value => Observable.of({ key: action.key, value }));
} else {
return Observable.of(action);
}
});
queue
.scan((state, action) => {
if (action.value instanceof Function) {
state[action.key] = action.value.call(null, state[action.key]);
} else {
state[action.key] = action.value;
}
return Object.assign({}, state);
}, initialState)
.subscribe(newState => {
provider.next(newState);
});
provider
.subscribe(state => {
console.log('state:', state);
});
setState('x', 2);
setState('y', Promise.resolve('b'));
setState('z', Observable.of(false));
setState('x', (p) => p + 1);
setState('y', Promise.resolve((p) => p + 'c'));
setState('z', Observable.of((p) => !p));
type Val<K extends keyof State> = State[K];
type Func<K extends keyof State> = (value: State[K]) => State[K];
function setState<K extends keyof State>(key: K, value: Val<K> | Func<K> | Promise<Val<K>> | Promise<Func<K>> | Observable<Val<K>> | Observable<Func<K>>) {
simpleStore.next({ key, value });
}
/* OUTPUT
state: { x: 1, y: 'a', z: true }
state: { x: 2, y: 'a', z: true }
state: { x: 2, y: 'b', z: true }
state: { x: 2, y: 'b', z: false }
state: { x: 3, y: 'b', z: false }
state: { x: 3, y: 'bc', z: false }
state: { x: 3, y: 'bc', z: true }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment