Skip to content

Instantly share code, notes, and snippets.

@crunchie84
Created April 4, 2018 19:08
Show Gist options
  • Save crunchie84/f212e3674ea02480431716bebd214ea3 to your computer and use it in GitHub Desktop.
Save crunchie84/f212e3674ea02480431716bebd214ea3 to your computer and use it in GitHub Desktop.
RxJs5 lifecycle debug operator
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/concat';
import 'rxjs/add/operator/finally';
import { Observable } from "rxjs";
/**
*
* Lifecycle debugging for your stream, sub/unsubscribe,complete and values
*
* @param this Observable
* @param identifier label to be outputted to console
*/
function debug<T> (this: Observable<T>, identifier: string): Observable<T> {
return Observable.empty<any>()
.do(_ => {}, undefined, () => console.log(`[${identifier}] subscribed`))
.concat(
this.do(
(val) => console.log(`[${identifier}] nextVal: ${val}`),
(err) => console.log(`[${identifier}] error: ${err.message}`),
() => console.log(`[${identifier}] completed`)
)
)
.finally(() => console.log(`[${identifier}] unsubscribed`));
};
Observable.prototype.debug = debug;
declare module "rxjs/Observable" {
interface Observable<T> {
debug: typeof debug;
}
}
import { Observable } from 'rxjs/Rx';
import "./debug";
const stream = Observable.interval(1000)
.take(3)
.debug("my-stream")
.subscribe()
;
/* outputs:
[my-stream] subscribed
[my-stream] nextVal: 0
[my-stream] nextVal: 1
[my-stream] nextVal: 2
[my-stream] nextVal: 3
[my-stream] completed
[my-stream] unsubscribed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment