Reactor-core: Add fold - operation to Flux

Created on 25 Nov 2019  路  5Comments  路  Source: reactor/reactor-core

It would be nice to see a new operator called fold for the Flux - type.

Motivation

Currently, a Flux can be accumulated using reduce only. Unfortunately, reduce does not emit an element for each accumulation, it will only emit the last result.
Other reactive libraries provide fold - methods for such purpose.

Desired solution

A method fold on Flux, with the following parameters:

  • Callable<A> initial
  • BiFunction<A, T, A> accumulator

When subscribed to, create an A (here: state) by evaluating initial. For every element, evaluate the accumulator using state and the element. Save the new result back in state and emit it as an element.

Considered alternatives

There aren't any really, except for implementing the aformentioned logic manually.

Additional context

I think there is enough other reactive libraries out there that have a similar operator.

statuinvalid

Most helpful comment

Okay. Thanks for the insight.

All 5 comments

There is Flux#scanWith for that

Thanks for the quick response, @bsideup .

Could we add an alias? As someone coming from a library like Monix, I couldn't find what I was looking for...

I think scan is popular enough:
https://www.scala-lang.org/api/current/scala/collection/Seq.html#scanB>:A(op:(B,B)=>B):CC[B]
https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/scan.html
http://reactivex.io/documentation/operators/scan.html
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.scan

Maybe Monix should change fold to scan? ;)

Jokes aside, we try to keep the set of operators small.
Having aliases usually causes more confusion and people are scary because there are so many of them that they don't know which one to choose.

Okay. Thanks for the insight.

Was this page helpful?
0 / 5 - 0 ratings