zoukankan      html  css  js  c++  java
  • [RxJS] Implement the `map` Operator from Scratch in RxJS

    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);
  • 相关阅读:
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业01--线性表
    C博客作业05--指针
    C语言博客作业04--数组
    C博客作业03--函数
    博客作业——循环结构
    C博客作业05-指针
    C博客作业04--数组
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9714609.html
Copyright © 2011-2022 走看看