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

  • 相关阅读:
    Docker contanier comunication with route
    Event Sourcing
    Event Sourcing
    Event Sourcing
    .Net async
    安装Docker
    【JQuery】数据
    【JQuery】遍历
    【JQuery】css操作
    【JQuery】文档操作
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9704509.html
Copyright © 2011-2022 走看看