Skip to content

Instantly share code, notes, and snippets.

@nite
Created March 4, 2021 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nite/15ef0796e63906dc096ebef50613f4e5 to your computer and use it in GitHub Desktop.
Save nite/15ef0796e63906dc096ebef50613f4e5 to your computer and use it in GitHub Desktop.
wrap function in mobx computed() and convert to rxjs observable
import { Observable } from 'rxjs';
import { computed, IValueDidChange } from 'mobx';
import isNil from 'lodash/isNil';
import omit from 'lodash/omit';
import { IEqualsComparer } from 'mobx/lib/internal';
interface ToObservableOptions<T> {
initial?: boolean;
equals?: IEqualsComparer<T>;
}
/***
* wrap function in mobx computed() and convert to observable
*
* @param observable - mobx observable property
* @param options - initial: whether to fire an initial event if the property is non-empty
*/
export function toObservable<T>(observable: () => T, options?: ToObservableOptions<T>): Observable<IValueDidChange<T>> {
const optionsToUse: ToObservableOptions<T> = { initial: true, ...options };
return new Observable((observer) => {
const fireInitial = isNil(optionsToUse.initial) || optionsToUse.initial;
const item = fireInitial && observable();
if (item) {
observer.next({
newValue: item,
object: item,
type: 'update',
oldValue: undefined,
});
}
computed(observable, omit(optionsToUse, ['initial'])).observe((item) => observer.next(item));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment