LoginSignup
15
11

More than 5 years have passed since last update.

RxJS mapとmergeMapの違い

Last updated at Posted at 2018-12-10

前提

rxjsについて、まだ何もわからない方は、こちらの記事を一度読んでいただけたらと思います。
https://tech.recruit-mp.co.jp/front-end/rxjs-intro/
と同時にこの記事では、

  • ストリーム
  • メッセージ
  • pipe
  • subscribe

について少し解説します。
特にストリーム、メッセージは、mapとmergeMapの説明でよく使います。

ストリーム

observableのことを指します。
const source = of(1,2)
上記は、ofによって、変数がsourceがobservableになっているので、変数sourceはストリームといえます。

メッセージ

ストリームの中に存在する値を指します。
const source = of(1,2)
ofの引数に、1と2を入れていることから、ストリームであるsourceは、メッセージ1と2をもつといえます。

pipeについて

オペレータを呼び出すためのメソッドです。
オペレータは、ストリームを操作します。
今回の主題である、map,mergeMapもオペレーターの区分に該当します。

//ストリームを作る
const number = of(1,2)
//numberのメッセージで、オペレータを使うことができる。
const map = number.pipe(
    map((x) => x ** 2))
//subscribeで値を購読
map.subscribe( val => console.log(val);
1
4

結局pipeとsubscribeの違いは?

  • pipeがオペレータを呼び出すためのメソッド
  • subscribeがストリームを購読するメソッドです。

Map

メッセージを処理して、新たなストリームを作成します。


//ストリーム作成
const source = of(1,2);
//各メッセージに10を足します。
const example = source.pipe(map(val => val + 10));

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

MergeMap

複数のストリームを一つのストリームにまとめます。


// ストリーム作成
const numbers = of(1,2,3);

//mergeMapの引数の中では、numbersストリームのメッセージごとに、新たなストリームを作成しています。
//つまり、ストリームの中で、複数のストリームができています。
//mergeMapによって、それを一つにまとめます。
const result = numbers.pipe(mergeMap(x => of(x)));

result.subscribe(x => console.log(x));

1
2
3

まとめ

  • mapは、メッセージを処理して、新たなストリームを作成します。
  • mergeMapは複数のストリームを一つのストリームにまとめます。

引用

http://reactivex.io/documentation/observable.html
https://t-cr.jp/article/3551640ea6a96e173
http://wilfrem.github.io/learn_rx/operators.html
http://reactivex.io/rxjs/file/es6/operator/mergeMap.js.html

15
11
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
15
11