RxJS之组合操作符 ( Angular环境 )

RxJS之组合操作符 ( Angular环境 )

大家好,又见面了,我是你们的朋友全栈君。

一 merge操作符

把多个 Observables 的值混合到一个 Observable 中

import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs/observable/of';
import { range } from 'rxjs/observable/range';
import { merge } from 'rxjs/observable/merge';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-combine',
  templateUrl: './combine.component.html',
  styleUrls: ['./combine.component.css']
})
export class CombineComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    const low: Observable<number> = range(100, 3);
    const middle: Observable<number> = range(200, 3);
    const high: Observable<number> = range(300, 3);
    merge(low, middle, high).subscribe((val: number) => {
      console.log(val);
    });
  }

}

RxJS之组合操作符 ( Angular环境 )

合并是没有顺序的:先到达的值在合并后的Observable中先输出。

import { Component, OnInit } from '@angular/core';
import { merge } from 'rxjs/observable/merge';
import { interval } from 'rxjs/observable/interval';
import { map } from 'rxjs/operators/map';
import { delay } from 'rxjs/operators/delay';

@Component({
  selector: 'app-combine',
  templateUrl: './combine.component.html',
  styleUrls: ['./combine.component.css']
})
export class CombineComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    let count = 0;
    const subscription = merge(
      interval(30).pipe(map(val => val + 300)),
      interval(40).pipe(map(val => val + 400)),
      interval(50).pipe(map(val => val + 500))
    ).pipe(delay(3000)) // 合并后的Observable,延迟3秒再开始的输出
      .subscribe(
        val => {
          count++;
          console.log(val);
          if (count >= 10) { // 只输出10个数
            subscription.unsubscribe();
          }
        }
      );
  }

}

RxJS之组合操作符 ( Angular环境 )

 二 forkJoin操作符

forkJoin will wait for all passed Observables to complete and then it will emit an array with last values from corresponding Observables.

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from 'rxjs/observable/forkJoin';
import { of } from 'rxjs/observable/of';

@Component({
  selector: 'app-combine',
  templateUrl: './combine.component.html',
  styleUrls: ['./combine.component.css']
})
export class CombineComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    forkJoin(
      of(1, 3, 5, 7),
      of(2, 4, 6, 8)
    ).subscribe(
      (arr: number[]) => {
        console.log(`next: ${arr[0]}, ${arr[1]}`);
      },
      null,
      () => {
        console.log('complete.');
      }
    );
  }

}

RxJS之组合操作符 ( Angular环境 )

处理并行的多个ajax请求 ( safari停止跨域限制 )

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from 'rxjs/observable/forkJoin';
import { of } from 'rxjs/observable/of';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-combine',
  templateUrl: './combine.component.html',
  styleUrls: ['./combine.component.css']
})
export class CombineComponent implements OnInit {

  constructor(public http: HttpClient) { }

  ngOnInit() {
    forkJoin(
      this.http.get('https://www.baidu.com', { responseType: 'text' }),
      this.http.get('https://www.sogou.com', { responseType: 'text' })
    ).subscribe(
      (arr: any[]) => {
        const baidu = arr[0].substring(arr[0].indexOf('<title>') + 7, arr[0].indexOf('</title>'));
        const sogou = arr[1].substring(arr[1].indexOf('<title>') + 7, arr[1].indexOf('</title>'));
        console.log(baidu);
        console.log(sogou);
      }
    );
  }
}

RxJS之组合操作符 ( Angular环境 )

三 startWith操作符

返回的 Observable 会先发出作为参数指定的项,然后再发出由源 Observable 所发出的项。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs/observable/of';
import { startWith } from 'rxjs/operators/startWith';

@Component({
  selector: 'app-combine',
  templateUrl: './combine.component.html',
  styleUrls: ['./combine.component.css']
})
export class CombineComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
    of('Mikey', 'Don').pipe(
      startWith('Leo', 'Raph')
    ).subscribe(
      (val: string) => {
        console.log(val);
      }
    );
  }
}

RxJS之组合操作符 ( Angular环境 )

 

转载于:https://www.cnblogs.com/sea-breeze/p/8969158.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/107554.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • setInterval与clearInterval

    setInterval与clearIntervalsetInterval 与 clearInterva 定义和用法语法返回值实例 setInterval 定义和用法 setInterval 方法可按照指定的周期 以毫秒计 来调用函数或计算表达式 setInterval 方法会不停地调用函数 直到 clearInterva 被调用或窗口被关闭 由 setInterval 返回的 ID 值可用作 clearInterva 方法的参数 语法 setInterval code millisec lang 参数描述

    2025年6月7日
    1
  • 将ASP.Net 2.0下的GridView导出为Excel.(转)

    将ASP.Net 2.0下的GridView导出为Excel.(转)

    2021年7月24日
    59
  • python变量命名规则

    python变量命名规则在Python中,变量标记或指向一个值。当遇到变量时,Python将其替换为指向值。>>>cost=2.99>>>.1*cost0.29900000000000

    2022年7月6日
    23
  • Optimal Keypad[通俗易懂]

    Optimal Keypad[通俗易懂]Description OptimusMobilesproducesmobilephonesthatsupportSMSmessages.TheMobileshaveakeypadof12keys,numbered1to12.Thereisacharacterstringassignedtoeachkey.Totypeinthe

    2022年4月28日
    33
  • matlab绘图颜色RGB

    matlab绘图颜色RGB目录1.MATLAB中颜色数值2.常用颜色3.matlab代码本文转载于https://www.jianshu.com/p/46af0b95ead7?tdsourcetag=s_pctim_aiomsg1.MATLAB中颜色数值2.常用颜色3.matlab代码semilogy(SNRs,mse,’Color’,[0.63,0.13,0.94],’Lin…

    2022年5月31日
    60
  • 机器学习:Multinoulli分布与多项式分布

    机器学习:Multinoulli分布与多项式分布学习深度学习时遇见multinoulli分布,在此总结一下机器学习中常用的multinoulli分布与多项式分布之间的区别于关系,以便更好的理解其在机器学习和深度学习中的使用。首先介绍一下其他相关知识。Bernoulli分布(两点分布)Bernoulli分布是单个二值随机变量的分布。它由单个参数控制,给出了随机变量等于1的概率。             …

    2022年10月12日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号