[RxJS] Implement the `map` Operator from Scratch in RxJS
2024-09-03 08:54:10
While it's great to use the RxJS built-in operators, it's also important to realize you now have the knowledge to write them by yourself if needed. The map
operator turns out to be a simple MapSubscriber
which takes a function and applies it to the value passed to next
.
map.js:
import { Subscriber } from "rxjs"; class MapSubscriber extends Subscriber {
constructor(sub, fn) {
super(sub);
this.fn = fn;
} _next(value) {
this.destination.next(this.fn(value));
}
} export const map = fn => source =>
source.lift({
call(sub, source) {
source.subscribe(new MapSubscriber(sub, fn));
}
});
multiply.js:
import { map } from "./map"; export const mul = number => map(v => v * number);
index.js:
import { from, Subscriber } from "rxjs";
import { multiply, mul } from "./multiply"; const observable$ = from([, , , , ]); const subscriber = {
next: value => {
console.log(value);
},
complete: () => {
console.log("done");
},
error: value => {
console.log(value);
}
}; observable$.pipe(mul()).subscribe(subscriber);
observable$.pipe(mul()).subscribe(subscriber);
最新文章
- VS2013中, 无法嵌入互操作类型“……”,请改用适用的接口的解决方法
- Quartz作业调度框架及时间表达式的含义和语法
- (Tree)94.Binary Tree Inorder Traversal
- 配置与使用 Git与Github
- codevs 1002 搭桥
- IOS中tableView每组的头部控件、通过tableView的代理方法控制某一行的cell能否达到高亮选中状态
- HTML5 面试中最常问到的 10 个问题
- hdu 1754 线段树模板题
- JSP EL表达式的运用
- JS中onload的各种使用
- Node.js新手教程——怎样实现文件上传功能
- Python3常用学习网站总结(随时更新)
- vuex Loding加载..
- android 与 服务器通信
- SQLite Where 子句(http://www.w3cschool.cc/sqlite/sqlite-where-clause.html)
- Python并发编程之线程中的信息隔离(五)
- Springboot项目配置druid数据库连接池,并监控统计功能
- vue的router-link传参问题
- week07 13.1 NewsPipeline之 一 NewsMonitor
- 《.NET之美》之程序集