import { createSubscriber } from "svelte/reactivity";

type Unsubscribe = () => void;
type EventSource<T> = { get: () => T; onChange: (notify: () => void) => Unsubscribe; };

export default class ReactiveEvent<T> {
    private _subscribe: () => void;
    private _source: EventSource<T>;

    constructor(source: EventSource<T>) {
        this._source = source;

        this._subscribe = createSubscriber((update) => {
            return this._source.onChange(() => {
                update();
            });
        });
    }

    get current(): T {
        this._subscribe();
        return this._source.get();
    }
}
