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的更多相关文章

  1. RxJS入门2之Rxjs的安装

    RxJS V6.0+ 安装 RxJS 的 import 路径有以下 5 种: 1.创建 Observable 的方法.types.schedulers 和一些工具方法 import { Observa ...

  2. [rxjs] Throttled Buffering in RxJS (debounce)

    Capturing every event can get chatty. Batching events with a throttled buffer in RxJS lets you captu ...

  3. [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 ...

  4. [RxJS] Combining streams in RxJS

    Source: Link We will looking some opreators for combining stream in RxJS: merge combineLatest withLa ...

  5. [RxJS] Error Handling in RxJS

    Get your code back on the happy path! This lesson covers a variety of ways to handle exceptions thro ...

  6. [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 ...

  7. rxjs入门4之rxjs模式设计

    观察者模式 (Observer Pattern) 观察者模式其实在日常编码中经常遇到,比如DOM的事件监听,代码如下 function clickHandler(event) { console.lo ...

  8. angular2 学习笔记 ( Rxjs, Promise, Async/Await 的区别 )

    Promise 是 ES 6 Async/Await 是 ES 7 Rxjs 是一个 js 库 在使用 angular 时,你会经常看见这 3 个东西. 它们都和异步编程有关,有些情况下你会觉得用它们 ...

  9. [转]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 ...

随机推荐

  1. How to convert a byte to its binary string representation

    How to convert a byte to its binary string representation For example, the bits in a byte B are 1000 ...

  2. jPlayer插件的使用

    文讲一下本人在使用jPlayer插件时的整个过程.出现的BUG已经解决办法. 最近在做bootstrap项目,项目中需要一个响应式.兼容IE7的视频播放插件,经过上网查找,找到了所谓可以兼容到IE6的 ...

  3. AIX 与Linux 中crontab 介绍

    AIX 与Linux 中crontab 用法相似,先介绍Linux 中的Crontab 用法,再后介绍AIX 与Linux 的不同之处.   一.Crontab 介绍 crontab命令的功能是在一定 ...

  4. 报错:System.Data.Entity.Validation.DbEntityValidationException: 对一个或多个实体的验证失败

    使用MVC和EF,在保存数据的时候报错:System.Data.Entity.Validation.DbEntityValidationException: 对一个或多个实体的验证失败.有关详细信息, ...

  5. Delphi中StrToDateTime函数TFormatSettings参数的使用

    var    FSetting : TFormatSettings;    DateTime1: tDateTime;  begin    FSetting := TFormatSettings.Cr ...

  6. firedac连接linux的oracle

    firedac连接linux的oracle 首先要下载并安装 oci for linux.OCI的版本要和ORACLE数据库的版本一致. centos7环境下安装OCI:https://blog.cs ...

  7. View Programming Guide for iOS_读书笔记[正在更新……]

    原文:View Programming Guide for iOS 1 Introduction 先熟悉一下基本概念. Window Windows do not have any visible c ...

  8. 关于面试总结5-python笔试题(递归)

    前言 本篇继续收集一些常见的python笔试题,以基础知识为主,递归是面试最喜欢考的一个问题,不管是做开发还是测试,都无法避免考递归.本篇结合实际案例,讲下几种关于递归的场景. 计算n的阶乘 计算n! ...

  9. Unity Shader-法线贴图(Normal)及其原理

    简介 以前经常听说“模型不好看啊,怎么办啊?”答曰“加法线”,”做了个高模,准备烘一下法线贴图”,“有的美术特别屌,直接画法线贴图”.....法线贴图到底是个什么鬼,当年天真的我真的被这个图形学的奇淫 ...

  10. YAML 语言教程

    编程免不了要写配置文件,怎么写配置也是一门学问. YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便. 本文介绍 YAML 的语法,以 JS-YAML 的实现为例.你可以去 ...