mobx-utils
Version:
Utility functions and common patterns for MobX
59 lines (58 loc) • 2.17 kB
TypeScript
export interface IStreamObserver<T> {
next?(value: T): void;
error?(error: any): void;
complete?(): void;
}
export interface ISubscription {
unsubscribe(): void;
}
export interface IObservableStream<T> {
subscribe(observer?: IStreamObserver<T> | null): ISubscription;
subscribe(observer?: ((value: T) => void) | null): ISubscription;
}
/**
* Converts an expression to an observable stream (a.k.a. TC 39 Observable / RxJS observable).
* The provided expression is tracked by mobx as long as there are subscribers, automatically
* emitting when new values become available. The expressions respect (trans)actions.
*
* @example
*
* const user = observable({
* firstName: "C.S",
* lastName: "Lewis"
* })
*
* Rx.Observable
* .from(mobxUtils.toStream(() => user.firstname + user.lastName))
* .scan(nameChanges => nameChanges + 1, 0)
* .subscribe(nameChanges => console.log("Changed name ", nameChanges, "times"))
*
* @export
* @template T
* @param {() => T} expression
* @param {boolean} fireImmediately (by default false)
* @returns {IObservableStream<T>}
*/
export declare function toStream<T>(expression: () => T, fireImmediately?: boolean): IObservableStream<T>;
/**
* Converts a subscribable, observable stream (TC 39 observable / RxJS stream)
* into an object which stores the current value (as `current`). The subscription can be cancelled through the `dispose` method.
* Takes an initial value as second optional argument
*
* @example
* const debouncedClickDelta = MobxUtils.fromStream(Rx.Observable.fromEvent(button, 'click')
* .throttleTime(1000)
* .map(event => event.clientX)
* .scan((count, clientX) => count + clientX, 0)
* )
*
* autorun(() => {
* console.log("distance moved", debouncedClickDelta.current)
* })
*/
export declare function fromStream<T>(observable: IObservableStream<T>): IStreamListener<T | undefined>;
export declare function fromStream<T, I>(observable: IObservableStream<T>, initialValue: I): IStreamListener<T | I>;
export interface IStreamListener<T> {
current: T;
dispose(): void;
}