Created
October 26, 2020 17:29
-
-
Save foxfriends/b38bd2b9f88b53b248b8991a6cbcaa75 to your computer and use it in GitHub Desktop.
Lenses for RxJS BehaviorSubjects
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 { 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