@ryanchenkie
Operators are what give you the power to be an RxJS Jedi but you need to know how to use the force
Your RxJS Jedi Training Begins Today
github.com/chenkie/custom-operators-workshop
Source Observable
Filter Operator
Combination Operator
Accumulation Operator
Final Output
const values = ['foo', 'bar', 'baz'];
const filteredValues = values.filter(v => v !== 'foo');
const valueStream = Rx.Observable.of('foo', 'bar', 'baz');
const filteredValueStream = valueStream.filter(v => v !== 'foo');
function addHello(source) {
return Rx.Observable.create(function(observer) {
source.subscribe(
function (value) {
observer.next(`Hello ${value}`);
},
function (err) {
observer.error(err)
},
function () {
observer.complete();
}
)
});
}
class FilterOperator<T> implements Operator<T, T> {
constructor(private predicate: (value: T, index: number) => boolean,
private thisArg?: any) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
}
}
class FilterSubscriber<T> extends Subscriber<T> {
count: number = 0;
constructor(destination: Subscriber<T>,
private predicate: (value: T, index: number) => boolean,
private thisArg: any) {
super(destination);
}
...
}
export class Subscriber<T> extends Subscription implements Observer<T> {
...
next(value?: T): void {
if (!this.isStopped) {
this._next(value);
}
}
error(err?: any): void {
if (!this.isStopped) {
this.isStopped = true;
this._error(err);
}
}
complete(): void {
if (!this.isStopped) {
this.isStopped = true;
this._complete();
}
}
}
public getUrl(): void {
this
.router
.events
.pipe(
filter(event => event instanceof NavigationStart),
filter((event: NavigationStart) => (/foo/).test(event.url))
)
.subscribe(event => {
console.log(event.url);
});
}
Thanks André Staltz!
@andrestaltz
Workshop Repo
github.com/chenkie/custom-operators-workshop
Workshop Repo
github.com/chenkie/custom-operators-workshop
(Don't reinvent the wheel)
const multiply = multiplyFn => (source: Observable<any>) => {
return new Observable(observer => {
return source.subscribe({
next(x: any) {
observer.next(multiplyFn(x));
},
error(err: any) {
observer.error(err);
},
complete() {
observer.complete();
}
});
});
};
this.obs
.pipe(multiply(x => x * 10))
.subscribe(x => console.log(x));
Workshop Repo
github.com/chenkie/custom-operators-workshop
@ryanchenkie
angularcasts.io
bit.ly/custom-operators