Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Rxにおけるscanとreduceの違い

More than 5 years have passed since last update.

TL;DR

  • reduceはcompleteするまで値が返らない
  • scanはnextで次々に値が返っていく
  • 値を逐次利用したい場合はscan使いましょう

他言語でのreduce

# in Ruby
# reduceはinjectのalias
(0..10).inject { |sum, n| sum + n }
// in JavaScript (ECMAScript 2015)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce((sum, n) -> sum + n)

Reduce operator

apply a function to each item emitted by an Observable, sequentially, and emit the final value

Screen Shot 2015-10-24 at 02.16.35.png

ReactiveX - Reduce operator

emit the final valueとあるように,結果をaccumulatorに溜め込んでいって最後(onComplete())に値を返す.
即ち,データが全て流れ切るまで次のメソッドに値は流れてこない.

Scan operator

apply a function to each item emitted by an Observable, sequentially, and emit each successive value

a6ffabb5-8e10-486d-a58e-ac28039d7fd6.png

ReactiveX - Scan operator

emit each successive valueとあるように,accumulatorの値を次々に(onNext())流してくれる.

即ち,データを1つ食えば1つ吐いてくれる.

どういうときに気をつければいいか

ひとつ前の結果を利用して値を変換し,その結果を逐次利用していく場合(センサ値にlow pass filterのようなものをかけるときとか)にreduceを使ってしまうと,センサ値読み出しをやめない限り値が返ってこない.Rubyist/JSerは反射的にreduceしそうになるけど,そこはグッとこらえてscan使いましょう.

References

wantedly
「シゴトでココロオドル」ためのビジネスSNS「Wantedly」の開発・運営をしています。
https://wantedlyinc.com/ja/presentations
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away