RxJS CombineLatest operator 的一个具体使用例子

简介: RxJS CombineLatest operator 的一个具体使用例子

CombineLatest 的使用场景:


This operator is best used when you have multiple, long-lived observables that rely on each other for some calculation or determination.


当有多个长时间存活的 Observable,且依赖彼此,共同完成某些计算逻辑时,适合使用 CombineLatest.


When any observable emits a value, emit the last emitted value from each.

image.png

import { Component, OnInit, Inject } from '@angular/core';
import { fromEvent, combineLatest } from 'rxjs';
import { mapTo, startWith, scan, tap, map } from 'rxjs/operators';
import { DOCUMENT } from '@angular/common';
@Component({
  selector: 'app-combine-latest',
  templateUrl: './combine-latest.component.html'
})
export class CombineLatestComponent implements OnInit {
  readonly document: Document;
  constructor(
    // https://github.com/angular/angular/issues/20351
    @Inject(DOCUMENT) document: any) {
      this.document = document as Document;
    }
  redTotal:HTMLElement;
  blackTotal: HTMLElement;
  total:HTMLElement;  
  test:HTMLElement;
  ngOnInit(): void {
    this.redTotal = this.document.getElementById('red-total'); 
    this.blackTotal = this.document.getElementById('black-total');
    this.total = this.document.getElementById('total');
    this.test = this.document.getElementById('test');
    combineLatest(this.addOneClick$('red'), 
    this.addOneClick$('black')).subscribe(([red, black]: any) => {
      this.redTotal.innerHTML = red;
      this.blackTotal.innerHTML = black;
      this.total.innerHTML = red + black;
    });
    fromEvent(this.test, 'click').pipe(map( event => event.timeStamp), mapTo(1)).subscribe((event) => console.log(event));
  }
  addOneClick$ = id =>
  fromEvent(this.document.getElementById(id), 'click').pipe(
    // map every click to 1
    mapTo(1),
    // keep a running total
    scan((acc, curr) => acc + curr, 0),
    startWith(0)
  );
}

效果:

  • 点击 Red 按钮,则 Red 计数器 和 Total 计数器 加 1
  • 点击 Black 按钮,则 Black 计数器 和 Total 计数器 加 1

image.png

image.png

image.png

image.pngimage.png

image.pngimage.png



相关文章
|
12月前
|
数据库连接 数据库
RxJs 里的 using operator 的使用场景介绍
RxJs 里的 using operator 的使用场景介绍
|
JavaScript
rxjs Observable filter Operator 的实现原理介绍
rxjs Observable filter Operator 的实现原理介绍
rxjs Observable 自定义 Operator 的开发技巧
rxjs Observable 自定义 Operator 的开发技巧
RxJs combineLatest Operator 的数组用法
RxJs combineLatest Operator 的数组用法
140 0
RxJs combineLatest Operator 的数组用法
rxjs operator学习笔记
rxjs operator学习笔记
102 0
rxjs operator学习笔记
rxjs里使用from operator从一个generator里生成Observable
rxjs里使用from operator从一个generator里生成Observable
76 0
rxjs里使用from operator从一个generator里生成Observable
rxjs 里的map operator
rxjs 里的map operator
105 0
rxjs 里的map operator
rxjs 里的pipe operator
rxjs 里的pipe operator
90 0
rxjs 里的pipe operator
rxjs里combineLatest operators的用法
rxjs里combineLatest operators的用法
110 0
rxjs里combineLatest operators的用法
rxjs里concatMap operators的用法
rxjs里concatMap operators的用法
115 0
rxjs里concatMap operators的用法