def foldM[U, T](zero: U)(f: (U, T) ⇒ Future[U]): Sink[T, Future[U]] = {
  Sink.fold[Future[U], T](Future.successful(zero)) { (fu, t) =>
    println(s"inside fold $t")
    fu.flatMap { x =>
      println(s"inside flatMap $x")
      f(x, t)
    }
  }.mapMaterializedValue(_ flatMap identity)
}

val result = Source(1 to 10).runWith(foldM(0)((a, x) => Future.successful(a + 
x)))

println(Await.result(result, 10.minutes))


prints:

inside fold 1
inside fold 2
inside fold 3
inside fold 4
inside fold 5
inside fold 6
inside fold 7
inside fold 8
inside flatMap 0
inside fold 9
inside fold 10
inside flatMap 1
inside flatMap 3
inside flatMap 6
inside flatMap 10
inside flatMap 15
inside flatMap 21
inside flatMap 28
inside flatMap 36

as you can see, the fold produces a stream of futures that are created 
instantly (I guess they are not technically unbounded because it's a fold, 
but there's no backpressure), while the actual folding operation happens on 
the executionContext you have in scope (because of the flatMap). 
That is basically the same as iteratively calling flatMap N times and 
waiting for the result, because we don't have backpressure.

Roland and everyone else: please correct me if I'm wrong!

Cheers

On Monday, 7 March 2016 21:08:15 UTC+1, Andrew Gaydenko wrote:
>
> On Sunday, March 6, 2016 at 2:28:22 AM UTC+3, Giovanni Alberto Caporaletti 
> wrote:
>>
>> Hi Roland,
>> you're right, my solution was a bit naive. I came up with this, I'm 
>> pretty sure it can be done in a better way, looking forward to seeing your 
>> solution :)
>>
>
> Giovanni, thanks for this graph - I use as example on reading streams doc 
> :)
> Have you idea how to provoke those "unbounded amounts of futures without 
> back pressure" Roland has wrote about? - to get OOME or.. what?
>

-- 
>>>>>>>>>>      Read the docs: http://akka.io/docs/
>>>>>>>>>>      Check the FAQ: 
>>>>>>>>>> http://doc.akka.io/docs/akka/current/additional/faq.html
>>>>>>>>>>      Search the archives: https://groups.google.com/group/akka-user
--- 
You received this message because you are subscribed to the Google Groups "Akka 
User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/akka-user.
For more options, visit https://groups.google.com/d/optout.

Reply via email to