Skip to content

Instantly share code, notes, and snippets.

@pyldin601
Last active June 22, 2018 06:51
Show Gist options
  • Save pyldin601/d87b8d42136dca140ef9092ee39b224d to your computer and use it in GitHub Desktop.
Save pyldin601/d87b8d42136dca140ef9092ee39b224d to your computer and use it in GitHub Desktop.
Small utility decorator for typescript and rxjs. It wraps method into stream that emits data when original function is called.
import { Subject } from 'rxjs/Subject';
export default function InvokeListener<T>(): MethodDecorator {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
const emitter$ = new Subject<T>();
const ngOnDestroy = target.ngOnDestroy;
target.ngOnDestroy = function () {
emitter$.complete();
if (ngOnDestroy) {
ngOnDestroy.call(this);
}
};
let isApplied = false;
descriptor.value = function (arg: T) {
if (!isApplied) {
original.call(this, emitter$);
isApplied = true;
}
emitter$.next(arg);
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment