Skip to content

Instantly share code, notes, and snippets.

@joost-de-vries
Last active October 28, 2016 19:13
Show Gist options
  • Select an option

  • Save joost-de-vries/4f0873b09b90d83dec93e0e5cdaa9ba4 to your computer and use it in GitHub Desktop.

Select an option

Save joost-de-vries/4f0873b09b90d83dec93e0e5cdaa9ba4 to your computer and use it in GitHub Desktop.
import {Observable} from "rxjs/Observable"
import {Subscriber} from "rxjs/Subscriber"
import {Operator} from "rxjs/Operator"
/**
* adds a 'debug' operator to rxjs/Observable
*
* example:
* import "./debug.observable"
*
* myObservable
* .debug("from my observable")
*/
function debug<T>(this: Observable<T>, message: string): Observable<T> {
return this.lift(new DebugOperator<T>(message))
}
class DebugOperator<T> implements Operator<T, T> {
constructor(private message: string) {
}
call(subscriber: Subscriber<T>, source: any): any {
return source._subscribe(new DebugSubscriber(subscriber, this.message))
}
}
class DebugSubscriber<T> extends Subscriber<T> {
constructor(destination: Subscriber<T>, private message: String) {
super(destination)
console.log(message, 'subscription')
}
protected _next(value: T) {
console.log(this.message, 'next', value)
this.destination.next(value)
}
protected _error(error: any) {
console.log(this.message, 'error', error)
this.destination.error(error)
}
protected _complete() {
console.log(this.message, 'complete')
this.destination.complete()
}
unsubscribe(): void {
console.log(this.message, 'unsubscribe')
super.unsubscribe();
}
}
Observable.prototype.debug = debug
declare module 'rxjs/Observable' {
interface Observable<T> {
debug: typeof debug
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment