0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[RxJS]combineLatest,combineLatestWith

Posted at

はじめに

RxJSのcombineLatestとcombineLatestWithについて学習したので、メモとして残しておきます。

combineLatest

公式の図がイメージしやすいです。
combineLatestは複数のObservableを登録し、それらのObservableが値を流すと、その値を配列にして返すObservableを作成します。

デモ

import { combineLatest, combineLatestWith, timer } from "rxjs";

const timer1 = timer(0, 1000)// 最初の値を0秒後に流し、その後は1秒ごとに値を流す
const timer2 = timer(2000, 3000)

const observable = combineLatest([timer1, timer2])

observable.subscribe(([timerVal1, timerVal2]) => {
    console.log(`Timer 1: ${timerVal1} Timer 2: ${timerVal2}`);
})

// Timer 1: 1 Timer 2: 0
// Timer 1: 2 Timer 2: 0
// Timer 1: 3 Timer 2: 0
// Timer 1: 4 Timer 2: 0
// Timer 1: 4 Timer 2: 1
// Timer 1: 5 Timer 2: 1

combineLatestWith

combineLatestWithの動作はcombineLatestと同じですが、使い方が異なります。combineLatestWithはインスタンスメソッドとして使用でき、既存のObservableに対して他のObservableを結合することが可能です。

デモ

実行結果はcombineLatestと同じ

import { combineLatest, combineLatestWith, timer } from "rxjs";

const timer1 = timer(0, 1000)
const timer2 = timer(2000, 3000)

timer1.pipe(combineLatestWith(timer2)).subscribe(([timerVal1, timerVal2]) => {
    console.log(`Timer 1: ${timerVal1} Timer 2: ${timerVal2}`);
})


// Timer 1: 1 Timer 2: 0
// Timer 1: 2 Timer 2: 0
// Timer 1: 3 Timer 2: 0
// Timer 1: 4 Timer 2: 0
// Timer 1: 4 Timer 2: 1
// Timer 1: 5 Timer 2: 1
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?