[RxJS] Implement the `map` Operator from Scratch in RxJS

本文详细介绍了如何从头开始实现RxJS的map操作符,通过创建自定义的MapSubscriber类来处理数据流的转换。同时,展示了如何使用自定义的multiply函数结合pipe和subscribe方法,对数组数据进行乘法运算。

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 mapoperator 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([1, 2, 3, 4, 5]);

const subscriber = {
  next: value => {
    console.log(value);
  },
  complete: () => {
    console.log("done");
  },
  error: value => {
    console.log(value);
  }
};

observable$.pipe(mul(3)).subscribe(subscriber);
observable$.pipe(mul(4)).subscribe(subscriber);

 

转载于:https://www.cnblogs.com/Answer1215/p/9714609.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值