• rxjs 常用的静态操作符


    Observable

    import { Observable } from "rxjs";
    
    const l = console.log;
    
    // 创建 Observable
    var observable = new Observable((subscribe) => {
      var id = setInterval(() => {
        subscribe.next(123);
        subscribe.error("err: ...");
        subscribe.complete();
      }, 1000);
    
      // 提供取消和清理 interval 资源的方法
      return function unsubscribe() {
        clearInterval(id);
      };
    });
    
    // 订阅 Observable
    var sub = observable.subscribe({ next: l, error: l, complete: l });
    
    // .add() 合并多个订阅,以便同时取消订阅
    // sub.add(childSubscription);
    
    // 撤销 add的合并
    // sub.remove(childSubscription);
    
    // 3s后取消订阅
    setTimeout(() => {
      sub.unsubscribe();
    }, 3000);
    
    

    of(...items)from([...items])

    按顺序发出每个元素, from 可以代替 fromPromise

    import { of, from } from "rxjs";
    
    of(1, 2, 3).subscribe(l); // 1,2,3
    
    from([1, 2, 3]).subscribe(l); // 1,2,3
    from( Promise.resolve(1) ).subscribe(l);  // 1
    from( Promise.resolve([1]) ).subscribe(l); // [1]
    

    bindCallback

    把普通的回调函数转化为 Observable

    import { bindCallback } from "rxjs";
    
    const test = (cb) => cb(1);
    let o$ = bindCallback(test)();
    o$.subscribe((v) => l(v)); // 1
    

    bindNodeCallback

    把标准的node回调函数转化为 Observable

    let { bindNodeCallback } = require("rxjs");
    let fs = require("fs");
    // fs.readFile("./test.jss", "utf8", (e, d) => (!!e ? l(e) : l(d)));
    
    let o$ = bindNodeCallback(fs.readFile)("./test.jss", "utf8");
    o$.subscribe(v => l(v), e => l(e));
    

    combineLatest

    组合多个流以创建一个流, 其值是根据每个输入流的最新值计算 (如果你要合并多个Subject就用这个)

    import { combineLatest, of, timer } from "rxjs";
    let o1$ = of(233);
    let o2$ = of(12);
    let o3$ = timer(0, 1000);
    
    combineLatest([o1$, o2$, o3$]).subscribe(l);
    
    // [ 233, 12, 0 ]
    // [ 233, 12, 1 ]
    // [ 233, 12, 2 ]
    // ...
    

    EMPTY

    仅仅发出 complete 通知,其他什么也不做

    let { EMPTY } = require("rxjs");
    EMPTY.subscribe(l, l, () => l("done")); // done
    

    forkJoin

    连接传递的Observables发出的最后一个值。

    let { forkJoin, of } = require("rxjs");
    forkJoin(of(1), of(2, 3)).subscribe(l); // [ 1, 3 ]
    

    merge

    把多个流的合并到一个 流, 按顺序执行,异步流会被延后

    import { merge, of, from } from "rxjs";
    merge(of(1), of(4), from(["a", "b"])).subscribe(l); // 1 4 a b
    

    concat

    它顺序地从给定的Observable中发出所有值,必须等上一个完成才执行下一个

    let { concat, interval, of } = require("rxjs");
    let { take } = require("rxjs/operators");
    
    let o1$ = interval(1000).pipe(take(4)); // take 接收源 最初的N个值
    let o2$ = of(233);
    
    concat(o1$, o2$).subscribe(l); // 0,1,2,3,233
    

    never

    创建一个不向观察者发出任何项的 Observable

    let { never } = require("rxjs");
    never().subscribe(l, l, () => l("done")); // 
    

    range

    发出指定范围内的数字序列

    import { range, toArray } from "rxjs";
    range(1,4).pipe( toArray() ).subscribe(l) // [ 1, 2, 3, 4 ]
    

    throwError

    仅仅发出 error 通知

    import { throwError } from "rxjs";
    throwError( () => new Error("err message") ).subscribe({ error: l }); // err message
    

    timer

    import { timer, interval } from "rxjs";
    
    // 延迟3秒发送第一个值,然后马上结束
    timer(3000).subscribe(l) // 0
      
    //每隔3s发送一个值,第一个值延迟5s
    timer(5000, 3000).subscribe(l)
    
    timer(0, 1000).subscribe(n => console.log('timer', n));
    interval(1000).subscribe(n => console.log('interval', n));
    

    interval

    在指定的时间间隔内发出序列号 0+

    let { interval } = require("rxjs");
    let { take } = require("rxjs/operators");
    interval(200).pipe( take(3) ).subscribe(l); // 0,1,2
    

    defer

    懒惰地创建Observable (订阅时创建)

    let { defer, of } = require("rxjs");
    let o$ = defer(() => Math.random() > 0.5 ? of(1) : of(2) );
    o$.subscribe(l);
    

    zip

    其值根据其每个输入Observable的值按顺序计算

    let { zip, of } = require("rxjs");
    let { map } = require("rxjs/operators");
    
    let age$ = of(27, 25, 29);
    let name$ = of("Foo", "Bar", "Beer");
    let isDev$ = of(true, true, false);
    
    zip(age$, name$, isDev$)
      .pipe(map(([age, name, isdev]) => ({ age, name, isdev })))
      .subscribe(l);
    
    // res
    { age: 27, name: 'Foo', isdev: true }
    { age: 25, name: 'Bar', isdev: true }
    { age: 29, name: 'Beer', isdev: false }
    

    iif

    在订阅时检查布尔值,并在两个可观察源之一之间进行选择

    import { iif, of } from "rxjs";
    iif(() => Math.random() > 0.5, of("then"), of("else")).subscribe(l); // then | else
    

    fromEvent

    给定事件触发时响应

    import { fromEvent } from "rxjs";
    const clicks$ = fromEvent(document, 'click');
    clicks$.subscribe(l);
    

    onErrorResumeNext

    将无错误地移动到下一个源

    let { onErrorResumeNext, of } = require("rxjs");
    let { map } = require("rxjs/operators");
    
    onErrorResumeNext(
      of(1, 2, 0, 1).pipe(
        map(el => {
          if (el === 0) throw Error("000");
          return el + el;
        }),
      ),
      of("2"),
    ).subscribe(l, err => console.error(err), () => l("done")); // 2, 4, 2, done
    

    pairs

    将对象转换为Observable

    let { pairs, of } = require("rxjs");
    pairs({
      name: "ajanuw",
      age: 14,
    }).subscribe(l); // [ 'name', 'ajanuw' ] [ 'age', 14 ]
    

    partition

    将源 Observable 拆分为两个,一个具有满足谓词的值,另一个具有不满足谓词的值

    import { partition, from, toArray } from "rxjs";
    
    const [needs$, nneeds$] = partition(from([2, 3, 4]), (i) => i <= 3);
    needs$.pipe( toArray() ).subscribe(l)  // [ 2, 3 ]
    nneeds$.pipe( toArray() ).subscribe(l) // [ 4 ]
    

    race

    返回,第一个Observable的反映的输出,然后结束

    let { race, of, interval } = require("rxjs");
    race(interval(1000), of(2, 22), of(3)).subscribe(l); // 2 22
    
  • 相关阅读:
    7617:输出前k大的数
    2991:2011
    7620:区间合并
    1688 求逆序对
    Magento How To Display Product Custom Option On list.phtml
    大二实习使用的技术汇总(中)
    codility上的问题 (22)
    poj 3321
    使用ViewPager实现左右“无限”滑动的万年历
    数论练习专题
  • 原文地址:https://www.cnblogs.com/ajanuw/p/8758002.html
Copyright © 2020-2023  润新知