Scala future combining -


imagine following variation of inputstream:

trait futureinputstream {   //read bytes asynchronously. empty array means eof   def read(): future[array[byte]] } 

question how write discardall function such stream? here solution:

//function discards input , returns future completed on eof def discardall(is: futureinputstream): future[unit] = {   val f = is.read()   f.flatmap {     case v if v.length == 0 =>       future successful unit     case _ =>       discardall(is)   } } 

obvious problem code non-optimizable recursion: run out of stack. there more efficient solution?

there nothing wrong solution. call discardall(is) done asynchronously. doesn't happen in same stack frame previous call, there no stack overflow.

you can kind of see happens naive implementation:

trait futureinputstream {      var count = 0      def read(): future[array[byte]] = {          if(count < 100000) {              count += 1              future(array(1))          } else              future(array())      } } 

if feed discardall instance of above, okay.

scala> val = new futureinputstream{} is: futureinputstream = $anon$1@255d542f  scala> discardall(is).oncomplete { println } success(()) 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -