zoukankan      html  css  js  c++  java
  • [RxJS] Create a Reusable Operator from Scratch in RxJS

    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);

  • 相关阅读:
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    从首页问答标题到问答详情页
    首页列表显示全部问答,完成问答详情页布局
    Android基础学习:Android环境搭建
    liunx 硬盘分区
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9704509.html
Copyright © 2011-2022 走看看