With knowledge of extending Subscriber and using source.lift to connect a source to a subscriber, you can now create your own operators by writing functions that return a source.lift call. This lesson creates a simple "multiply" operator in RxJS.
index.js:
import { from, Subscriber } from "rxjs";
import { multiply } from "./multiply";
const observable$ = from([1, 2, 3, 4, 5]);
const subscriber = {
next: value => {
console.log(value);
},
complete: () => {
console.log("done");
},
error: value => {
console.log(value);
}
};
observable$.pipe(multiply(3)).subscribe(subscriber);
multiply.js:
import { Subscriber } from "rxjs";
class MultiplySubscriber extends Subscriber {
constructor(subscriber, number) {
super(subscriber);
this.number = number;
}
_next(value) {
this.destination.next(value * this.number);
}
}
export const multiply = number => source => {
return source.lift({
call(sub, source) {
source.subscribe(new MultiplySubscriber(sub, number));
}
});
};
The most common scenario for creating custom operators is to reuse the built-in operators shipped with RxJS. You'll find yourself re-using map, filter, and others will solve most of the problems you come across.
import { map } from "rxjs/operators";
export const mul = number => map(v => v * number);
本教程介绍如何使用RxJS库创建自定义操作符。通过扩展Subscriber类并利用source.lift方法,可以实现如乘法等操作符。示例代码展示了如何创建一个名为'multiply'的操作符,并将其应用于Observable实例,将接收到的每个值乘以指定的数字。
756

被折叠的 条评论
为什么被折叠?



