Skip to content

Instantly share code, notes, and snippets.

@foxfriends
Created October 26, 2020 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxfriends/b38bd2b9f88b53b248b8991a6cbcaa75 to your computer and use it in GitHub Desktop.
Save foxfriends/b38bd2b9f88b53b248b8991a6cbcaa75 to your computer and use it in GitHub Desktop.
Lenses for RxJS BehaviorSubjects
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { get, set } from 'shades';
class Lens extends Observable {
#lens;
#source;
constructor(source, lens) {
if (!(source instanceof BehaviorSubject)) {
throw new TypeError('Source of a lens must be a BehaviorSubject');
}
super((observer) => source
.pipe(map(get(...lens)))
.subscribe(observer));
this.#lens = lens;
this.#source = source;
}
set(value) {
source.next(set(...this.#lens)(value)(this.#source.getValue()));
}
}
function LensBuilder(lens = []) {
return new Proxy(() => {}, {
get(target, prop, receiver) {
return LensBuilder([...lens, prop]);
},
apply(target, self, args) {
const source = args[0] ?? self;
return new Lens(source, lens);
},
});
}
export default LensBuilder();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment