[RxJS] Create a Reusable Operator from Scratch in RxJS

本教程介绍如何使用RxJS库创建自定义操作符。通过扩展Subscriber类并利用source.lift方法,可以实现如乘法等操作符。示例代码展示了如何创建一个名为'multiply'的操作符,并将其应用于Observable实例,将接收到的每个值乘以指定的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 mapfilter, and others will solve most of the problems you come across.

import { map } from "rxjs/operators";
export const mul = number => map(v => v * number);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值