43
31

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 5 years have passed since last update.

Rxにおけるscanとreduceの違い

Posted at

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

43
31
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
43
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?