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);
  • 相关阅读:
    北航OO第三单元总结
    北航OO第二单元总结
    提问回顾和个人总结
    Unity 制作不规则形状button
    Unity 3D手游对不同分辨率屏幕的UI自适应
    软工结队作业
    CSDN app分析
    软工作业——求交点
    软工第一次作业
    软工热身作业
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9714609.html
Copyright © 2011-2022 走看看