rxjs 操作符 pairwise 的一个例子

简介: rxjs 操作符 pairwise 的一个例子

Groups pairs of consecutive emissions together and emits them as an array of two values.


pairwise 将连续的发射出的值进行分组并配对,然后以数组的数据结构进行发射。


pairwise 返回的数据类型如下:返回一个新的 OperatorFunction,这是一个函数,该函数返回一个新的 Observable,以数组的结构包裹了源 Observable 发射的值。


OperatorFunction<T, [T, T]>: A function that returns an Observable of pairs (as arrays) of consecutive values from the source Observable.

pairwise 的弹珠图:

下列这段代码,计算每次屏幕点击和前一次点击的绝对距离:

import { fromEvent } from 'rxjs';
import { pairwise, map } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const pairs = clicks.pipe(pairwise());
const distance = pairs.pipe(
  map((pair) => {
    const x0 = pair[0].clientX;
    const y0 = pair[0].clientY;
    const x1 = pair[1].clientX;
    const y1 = pair[1].clientY;
    return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
  })
);
distance.subscribe((x) => console.log(x));


相关文章
|
12月前
|
缓存 JavaScript 前端开发
RxJS系列05:操作符 Operators(下)
RxJS系列05:操作符 Operators(下)
|
10月前
rxjs ThrottleTime 和 debounceTime 的操作符区别
rxjs ThrottleTime 和 debounceTime 的操作符区别
|
12月前
|
JavaScript 前端开发 Go
RxJS系列04:操作符 Operators(上)
RxJS系列04:操作符 Operators(上)
|
Python
【Python函数式编程】——偏函数(Partial function)
 Python的 functools 模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。要注意,这里的偏函数和数学意义上的偏函数不一样。
172 0
【Python函数式编程】——偏函数(Partial function)
rxjs 操作符 pairwise 的一个例子
rxjs 操作符 pairwise 的一个例子
82 0
rxjs 操作符 pairwise 的一个例子
|
C语言 Python
【Python函数式编程】——高阶函数(Higher-order function)
函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。
197 0
【Python函数式编程】——高阶函数(Higher-order function)
rxjs里concat operators的用法
rxjs里concat operators的用法
126 0
rxjs里concat operators的用法
|
JavaScript
rxjs里distinctUntilChanged operators的用法
rxjs里distinctUntilChanged operators的用法
104 0
rxjs里distinctUntilChanged operators的用法
rxjs里concatMap operators的用法
rxjs里concatMap operators的用法
105 0
rxjs里concatMap operators的用法
rxjs里withLatestFrom operators的用法
rxjs里withLatestFrom operators的用法
100 0
rxjs里withLatestFrom operators的用法

热门文章

最新文章