[RxJS] Build your own RxJS
JavaScript has multiple APIs that use callback functions that all do nearly the same thing with slight variations. Event listeners, array methods such as .forEach
, promises, and NodeJS streams all are very close in the way they are written. Instead, in RxJS you'd unify all of these APIs under one abstraction.
Normal RxJS API:
import { from } from "rxjs";
import { map, filter } from "rxjs/operators"; from([, , , ])
.pipe(map(x => x * ))
.pipe(filter(x => x < ))
.subscribe(val => console.log(val));
// 2
//
We can build our own RxJS operator
First, Observable,
it has API:
{
subscribe() {}
pipe() {}
}
We can create a function call 'createObservable(subscribe)', take a subscribe function, return a subscribe and pipe function:
function createObservable(subscribe) {
return {
subscribe,
pipe(operator) {
return operator(this);
}
};
}
We can use it to create Observables:
const numberObservable = createObservable(function(observer) {
[, , , ].forEach(x => {
observer.next(x);
}); observer.complete();
}); const clickObservable = createObservable(function(observer) {
document.addEventListener("click", function(ev) {
observer.next(ev);
});
});
Second, Observer:
Observer is easy, it takes a object which contains 'next', 'error', 'complete' functions:
const observer = {
next(x) {
console.log(x);
},
error(err) {
console.error(err);
},
complete() {
console.log("DONE");
}
};
Third, Operator, map, filter:
map(fn)(observable)
filter(predFn)(observable)
It is important to know that map & filter, those operator, takes an inputObservable and will return an outputObservable.
We subscribe inputObservable, and inputObserver, inside inputObserver, we call outputObserver which is passed in from the consumer.
const map = fn => inputObservable => {
const outputObservable = createObservable(function(outputObserver) {
const observer = {
next(x) {
const res = fn(x);
outputObserver.next(res);
},
error(err) {
outputObserver.error(err);
},
complete() {
outputObserver.complete();
}
};
inputObservable.subscribe(observer);
}); return outputObservable;
}; const filter = fn => inputObservable => {
const outputObservable = createObservable(function(outputObserver) {
const observer = {
next(x) {
if (fn(x)) {
outputObserver.next(x);
}
},
error(err) {
outputObserver.error(err);
},
complete() {
outputObserver.complete();
}
};
inputObservable.subscribe(observer);
}); return outputObservable;
};
--
Full Code:
function createObservable(subscribe) {
return {
subscribe,
pipe(operator) {
return operator(this);
}
};
} const numberObservable = createObservable(function(observer) {
[, , , ].forEach(x => {
observer.next(x);
}); observer.complete();
}); const clickObservable = createObservable(function(observer) {
document.addEventListener("click", function(ev) {
observer.next(ev);
});
}); const map = fn => inputObservable => {
const outputObservable = createObservable(function(outputObserver) {
const observer = {
next(x) {
const res = fn(x);
outputObserver.next(res);
},
error(err) {
outputObserver.error(err);
},
complete() {
outputObserver.complete();
}
};
inputObservable.subscribe(observer);
}); return outputObservable;
}; const filter = fn => inputObservable => {
const outputObservable = createObservable(function(outputObserver) {
const observer = {
next(x) {
if (fn(x)) {
outputObserver.next(x);
}
},
error(err) {
outputObserver.error(err);
},
complete() {
outputObserver.complete();
}
};
inputObservable.subscribe(observer);
}); return outputObservable;
}; const observer = {
next(x) {
console.log(x);
},
error(err) {
console.error(err);
},
complete() {
console.log("DONE");
}
}; numberObservable
.pipe(map(x => x * ))
.pipe(map(x => x - ))
.subscribe(observer); clickObservable
.pipe(map(ev => [ev.clientX, ev.clientY]))
.pipe(filter(([x, y]) => x < && y < ))
.subscribe(observer);
[RxJS] Build your own RxJS的更多相关文章
- RxJS入门2之Rxjs的安装
RxJS V6.0+ 安装 RxJS 的 import 路径有以下 5 种: 1.创建 Observable 的方法.types.schedulers 和一些工具方法 import { Observa ...
- [rxjs] Throttled Buffering in RxJS (debounce)
Capturing every event can get chatty. Batching events with a throttled buffer in RxJS lets you captu ...
- [RxJS] Stream Processing With RxJS vs Array Higher-Order Functions
Higher order Array functions such as filter, map and reduce are great for functional programming, bu ...
- [RxJS] Combining streams in RxJS
Source: Link We will looking some opreators for combining stream in RxJS: merge combineLatest withLa ...
- [RxJS] Error Handling in RxJS
Get your code back on the happy path! This lesson covers a variety of ways to handle exceptions thro ...
- [RxJS 6] The Retry RxJs Error Handling Strategy
When we want to handle error observable in RxJS v6+, we can use 'retryWhen' and 'delayWhen': const c ...
- rxjs入门4之rxjs模式设计
观察者模式 (Observer Pattern) 观察者模式其实在日常编码中经常遇到,比如DOM的事件监听,代码如下 function clickHandler(event) { console.lo ...
- angular2 学习笔记 ( Rxjs, Promise, Async/Await 的区别 )
Promise 是 ES 6 Async/Await 是 ES 7 Rxjs 是一个 js 库 在使用 angular 时,你会经常看见这 3 个东西. 它们都和异步编程有关,有些情况下你会觉得用它们 ...
- [转]VS Code 扩展 Angular 6 Snippets - TypeScript, Html, Angular Material, ngRx, RxJS & Flex Layout
本文转自:https://marketplace.visualstudio.com/items?itemName=Mikael.Angular-BeastCode VSCode Angular Typ ...
随机推荐
- HDU 4745 Two Rabbits (2013杭州网络赛1008,最长回文子串)
Two Rabbits Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Tota ...
- systemtap跟踪C
1.[root@localhost ~]# rpm -qi glibcName : glibc Relocations: (not rel ...
- C程序设计的抽象思维-递归过程-砝码称重
[问题] 在狄更斯时代,商人们用砝码和天平来称量商品的重量,假设你仅仅有几个砝码,就仅仅能精确地称出一定的重量.比如,假定仅仅有两个砝码:各自是1kg和3kg. 仅仅用1kg的砝码能够称出1kg重量的 ...
- [转载]vs2017与docker
基本需求 系统 win10 vs2017 docker 步骤 1.开启系统的hyper-v 2. 重启电脑 3.安装docker 下载地址:https://docs.docker.com/docker ...
- Warning: The Copy Bundle Resources build phase contains this target's Info.plist file 'Info
WARNING: The Copy Bundle Resources build phase contains this target's Info.plist file 'Info.plist'. ...
- WordPress主题开发:WP_Query使用分页实例
functions.php加入 <?php function lingfeng_custom_pagenavi( $custom_query,$range = 4 ) { global $pag ...
- linux下一个网卡配置多个IP
转自:http://blog.csdn.net/beckdon/article/details/15815197 最常用的给网卡配置ip的命令为 #ifconfig eth0 192.168.0.1 ...
- nodeJS 相关开源项目
摘要:NodeJS是一个服务器端JavaScript解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处理数万条同时连接到一个(只有一个)物理机的连接代码 ...
- Android应用icon和闪屏splash的尺寸
icon (尺寸为px) 目录 尺寸 (width * height) drawable 72 x 72 drawable-hdpi 72 x 72 drawable-ldpi 36 x 36 dra ...
- bash 设置
export COLUMNS=500 $* 将所有命令行参数当做单个文本值包含 $@ 将所有命令行参数当做独立的文本值包含 $# 命令行参数数目 $? 最近使用的前端进程的退出状态码 $- 当前命令选 ...