Skip to content

Instantly share code, notes, and snippets.

@deebloo
Created May 15, 2018 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deebloo/7f5bcb9a2cc78b08e189b10d7038e2c0 to your computer and use it in GitHub Desktop.
Save deebloo/7f5bcb9a2cc78b08e189b10d7038e2c0 to your computer and use it in GitHub Desktop.
import { BehaviorSubject, of } from 'rxjs';
import { distinctUntilChanged, concatMap, map, take } from 'rxjs/operators';
export class StateDef<T> extends BehaviorSubject<T> {
setState(setter: (state: T) => T) {
this.pipe(take(1)).subscribe(state => {
super.next(setter(state));
});
}
select<R>(selector: (state?: T) => R) {
return this.pipe(map(selector), distinctUntilChanged());
}
selectOnce<R>(selector: (state?: T) => R) {
return this.select(selector).pipe(take(1));
}
next() {
throw new Error('Nice Try, Use setState instead of next.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment