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?

More than 3 years have passed since last update.

【RxJS】mergeMapはmap+subscribe

Last updated at Posted at 2021-06-12

mergeMapはmap+subscribeと考えるとわかりやすい

以下の例ではストリームの中にストリームを作成しているため、中の値を取り出すのに2回subscribeが必要となってしまっています。

import { of, from } from 'rxjs'; 
import { map, delay } from 'rxjs/operators';

const getData = (param) => {
  return of(`retrieved new data with param ${param}`).pipe(
    delay(1000)
  )
}

from([1,2,3,4]).pipe(
  map(param => getData(param))
).subscribe(val => val.subscribe(data => console.log(data)));

そこで、mergeMapの出番です。

import { of, from } from 'rxjs'; 
import { map, delay } from 'rxjs/operators';

const getData = (param) => {
  return of(`retrieved new data with param ${param}`).pipe(
    delay(1000)
  )
}
from([1,2,3,4]).pipe(
  mergeMap(param => getData(param))
).subscribe(val => console.log(val));

mergeMapがmapを実行した後に内側のストリームと外側のストリームをマージしてくれます。
map+subscribeと考えると分かりやすいと思います。

以下の記事を参考にさせていただきました。

https://luukgruijs.medium.com/understanding-rxjs-map-mergemap-switchmap-and-concatmap-833fc1fb09ff#:~:text=MergeMap%20essentially%20is%20a%20combination,into%20the%20'outer'%20Observable.

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?