openreplay/frontend/app/player/common/StoreSubscriber.ts
Alex Kaminskii ecf4e0e8a2 whatewer
2023-04-21 18:08:07 +02:00

23 lines
No EOL
661 B
TypeScript

import { Store } from './types'
export default class StoreSubscriber<G, S=G> implements Store<G, S> {
constructor(private store: Store<G, S>) {}
get() { return this.store.get() }
update(newState: Partial<S>) {
this.store.update(newState)
this.subscriptions.forEach(sb => sb())
}
private subscriptions: Function[] = []
subscribe<T>(selector: (g: G) => T, cb: (val: T) => void) {
let prevVal = selector(this.get())
const checkSubscription = () => {
const newVal = selector(this.get())
if (newVal !== prevVal) {
prevVal = newVal
cb(newVal)
}
}
this.subscriptions.push(checkSubscription)
}
}