Rxjs 操作符实践指南

2023-11-07

操作符实战

1.工具方法型

count

  • 统计总数
import { range } from 'rxjs';
import { count } from 'rxjs/operators';

const numbers = range(1, 7);
const result = numbers.pipe(count(i => i % 2 === 1));
result.subscribe(x => console.log(x));
// Results in:
// 4

reduce

  • 累计
import { fromEvent, interval } from 'rxjs';
import { reduce, takeUntil, mapTo } from 'rxjs/operators';

const clicksInFiveSeconds = fromEvent(document, 'click').pipe(
  takeUntil(interval(5000)),
);
const ones = clicksInFiveSeconds.pipe(mapTo(1));
const seed = 0;
const count = ones.pipe(reduce((acc, one) => acc + one, seed));
count.subscribe(x => console.log(x));

max\min

import { of,merge } from 'rxjs';
import { max,min,tap } from 'rxjs/operators';

const obs$ = of(5, 4, 7, 2, 8);
merge(
    obs$.pipe(max()),
    obs$.pipe(min()),
).pipe(tap((val) => {
    console.log("result....",val);
})).subscribe(console.log);

//output
result.... 8
8
result.... 2
2

tap

日志输出
of 是一个个输出的

import { of,merge } from 'rxjs';
import { max,min,tap } from 'rxjs/operators';

const obs$ = of(5, 4, 7, 2, 8);
obs$.pipe(tap({
    next:(val) => {
        console.log("val",val);
    },
    error:() => {

    },
    complete:() => {

    }
})).subscribe(console.log)

//output
val 5
5
val 4
4
val 7
7
val 2
2

repeat

重复 === 多次订阅

import { tap } from 'rxjs/operators';
// RxJS v6+
import { repeat, delay } from 'rxjs/operators';
import { of } from 'rxjs';

const delayedThing = of('delayed value').pipe(
        tap(() => {
            console.log("time..1.",new Date().toLocaleTimeString());
        }),
        delay(2000)
        );

delayedThing
  .pipe(
    tap(() => {
        console.log("time...2",new Date().toLocaleTimeString());
    }),
      repeat(3)
    )
  .subscribe(console.log);

//output 
time..1. 4:42:45 PM
time...2 4:42:47 PM
delayed value
time..1. 4:42:47 PM
time...2 4:42:49 PM
delayed value
time..1. 4:42:49 PM
time...2 4:42:51 PM
delayed value

subscribeOn, observeOn

  • 调整执行时机,
import { of, merge } from 'rxjs';

const a = of(1, 2, 3, 4);
const b = of(5, 6, 7, 8, 9);
merge(a, b).subscribe(console.log);
// 1 2 3 4 5 6 7 8 9


import { of, merge, asyncScheduler } from 'rxjs';
import { subscribeOn } from 'rxjs/operators';

const a = of(1, 2, 3, 4).pipe(subscribeOn(asyncScheduler));
const b = of(5, 6, 7, 8, 9);
merge(a, b).subscribe(console.log);
//5 6 7 8 9 1 2 3 4


import { interval } from 'rxjs';
import { observeOn } from 'rxjs/operators';

const intervals = interval(10);                // Intervals are scheduled
                                              // with async scheduler by default...
intervals.pipe(
  observeOn(animationFrameScheduler),          // ...but we will observe on animationFrame
)                                              // scheduler to ensure smooth animation.
.subscribe(val => {
  someDiv.style.height = val + 'px';
});

materialize

  • 用默认对象包箱, dematerialize 开箱
import { of } from 'rxjs';
import { materialize, map } from 'rxjs/operators';

const letters = of('a', 'b', '13', 'd');
const upperCase = letters.pipe(map(x => x.toUpperCase()));
const materialized = upperCase.pipe(materialize());
materialized.subscribe(x => console.log(x));

Notification { kind: 'N', value: 'A', error: undefined, hasValue: true }
Notification { kind: 'N', value: 'B', error: undefined, hasValue: true }
Notification { kind: 'N', value: '13', error: undefined, hasValue: true }
Notification { kind: 'N', value: 'D', error: undefined, hasValue: true }
Notification { kind: 'C', value: undefined, error: undefined, hasValue: false }

timestamp

  • 添加时间戳
 import { of } from 'rxjs';
 import { materialize, map, timestamp, tap } from 'rxjs/operators';

 const letters = of('a', 'b', '13', 'd');

 const times = letters.pipe(timestamp());
 times.subscribe(res => {
     console.log("res...",res)
 });

//output 
 res... Timestamp { value: 'a', timestamp: 1594074567694 }
 res... Timestamp { value: 'b', timestamp: 1594074567700 }
 res... Timestamp { value: '13', timestamp: 1594074567700 }
 res... Timestamp { value: 'd', timestamp: 1594074567700 }

toArray

最终结果toArray,取决于source是一个个产生的,map,filter,interval

 import { interval } from 'rxjs';
 import { toArray, take } from 'rxjs/operators';

 const source = interval(1000);
 const example = source.pipe(
   take(10),
   toArray()
 );

 const subscribe = example.subscribe(val => console.log(val));

 // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rxjs 操作符实践指南 的相关文章

随机推荐

  • MonoSQL--支持SQL,让DynamoDB更强大

    MonoSQL from MonographDB MonoSQL是成章数据打造的一款基于DynamoDB的分布式SQL数据库 受益于DynamoDB的Serverless架构和任何数据规模下的查询个位数延时保障 MonoSQL在支持SQL生
  • PCB板上字母的含义

    阅读PCB板子文件 发现板子上字母的大致符合表中规律 PCB板上 字母 数字 如R16 C16 表示的含义 一般数字表示出现的次数 字母表示的意义如下 字母 含义 R 电阻 C 电容 K 继电器 L 电感 U 整流器 字母的意义并非始终与表
  • 问题记录setStyleSheet:Qt样式表频繁设置导致CPU占用过高问题

    一 问题 APP控件 QWidget 主窗口 背景利用setStyleSheet设置 同时重写paintEvent事件 QWigdet的paintEvent默认为空 void mainWidget paintEvent QPaintEven
  • Java数组转Json数组

    package com cnic test coding import com alibaba fastjson JSONArray public class ArrToJson public static void main String
  • Java中为什么要重写hashCode方法和equals方法?重写了equals方法为什么还要重写hashCode方法? 啊~~终于明白了

    在我们开发中 可能经常听到重写hashCode方法和equals方法 这是为什么呢 为了更容易通俗易懂 来个小故事缓解一下激动的心情 打个比方 一个名叫张三的人去住酒店 在前台登记完名字就去了99层100号房间 此时警察来前台找叫张三的这个
  • 查询数据库所占空间大小

    目录 统计数据库整体所占大小 统计数据库中各表所占大小 统计数据库整体所占大小 select table schema as 数据库 sum table rows as 记录数 sum truncate data length 1024 1
  • 华为19级专家10年心血终成百页负载均衡高并发网关设计实战文档

    负载均衡 LoadBalance 的字面意思是将工作负载分担到多个工作单元上进行执行 它建立在现有网络结构之上 是构建分布式服务 大型网络应用的关键组件 近十几年来 负载均衡技术层出不穷 令人眼花缭乱 如果问身边的技术人员什么是负载均衡 我
  • Vjava学习笔记之(VirtualMachine 内存(总容量和已使用))

    源代码 package com vmware client import com vmware util Session import com vmware vim25 HostListSummary import com vmware v
  • 11G RAC 中 OCR 及Voting Disk 相关操作

    一 启动oracle clusterware 先决条件 Oracle High Availability Services daemon OHASD 运行在所有集群节点上 1 启动整个Oracle Clusterware stack crs
  • windows下git

    下载gitGit for Windows Windows安装git图文教程 喵代王 香菜的博客 CSDN博客 windows安装git 创建文件夹 右键 git bash here 同mac使用
  • 基于Spring Boot的ERP仓储管理信息系统设计与实现毕业设计源码150958

    基于Spring Boot的ERP仓储管理信息系统设计与实现 摘 要 科技进步的飞速发展引起人们日常生活的巨大变化 电子信息技术的飞速发展使得电子信息技术的各个领域的应用水平得到普及和应用 信息时代的到来已成为不可阻挡的时尚潮流 人类发展的
  • 如何实现一个IO口读取多个设备信息

    前言 1 今天遇到一个有意思的问题一个IO口如何读取多个电机的堵转问题 之后他就发了一张图片 2 看到这个问题 之前先说一个简单的 我们如何实现一个IO读取多个按键 了解了这个之后 对于多个电机堵转就很好理解了 如何实现一个IO对多个按键读
  • 直方图均衡化原理

    原文 http www cnblogs com tianyalu p 5687782 html 直方图均衡化原理 直方图均衡化的作用是图像增强 有两个问题比较难懂 一是为什么要选用累积分布函数 二是为什么使用累积分布函数处理后像素值会均匀分
  • 从零开始的Java开发 笔记目录(跑路了)

    写在前面 不全 学习资料来源于网络 已经跑路了 文章目录 阶段1 Java零基础入门 第1周 环境搭建与语法入门 第2周 Java语法之循环 数组与方法 第3周 面向对象之封装与继承 第4周 面向对象之单例模式与多态 第5周 常用工具类 上
  • linux c++遍历文件夹下所有文件,C++ 遍历目录下文件

    function 遍历目录下所有文件 返回文件总数 子文件夹总数 修改一下可以获得全部文件名等 include stdlib h include direct h include string h include io h include
  • 对OOD/OOP有较深的理解

    最近 经常有很多人在求职的时候遇到这样一个问题 对OOD OOP有较深的理解 那OOD OOP又是什么 那今天就来讲讲它们都是些什么 又如何去回答 1 OOA Object oriented analysis 面向对象分析 面向对象分析方法
  • 一款带ai基因的向导般生成ppt的神奇网站

    只要按要求填写每一页的内容 即可生成一套像模像样的ppt 无需排版 模板众多 以后ppt不需要人写了 哈哈 1 登录 https app slidebean com 2 注册 3 新建 4 模板选择 5 填写 以airbnb为例 6 结果
  • 【微信读书每日一答辅助小程序】使用python对每日一答问题进行识别,并将结果保存到剪贴板以便搜索。

    目录标题 1 环境准备 2 获取屏幕位置 3 指定区域屏幕截图 4 文字识别 5 按键识别并保存到剪贴板 在腾讯收购阅文之后 微信读书的无限卡已经不能免费看书了 这时白嫖微信读书每日一答的书币成了不错的选择 严重偏科又手速垃圾的我在等级升高
  • Win10 解决docker一直docker desktop starting进不去的问题

    这里写自定义目录标题 为什么出现这个问题 方法1 方法2 方法3 解决我的问题 后续计划 为什么出现这个问题 似乎是因为上次没有完全关闭 而是直接关闭电脑导致的 目前有三种方法 后续应该有更多 我这边方法1 2都没有解决我的问题 方法3解决
  • Rxjs 操作符实践指南

    操作符实战 1 工具方法型 count 统计总数 import range from rxjs import count from rxjs operators const numbers range 1 7 const result nu