Search code examples
scalaplayframeworkenumeratorwriterplayframework-2.3

Play framework: how to enumerate java.io.Writer?


An external library uses java.io.Writer interface for some kind of output, and at the moment I use StringWriter to buffer all output and then Ok(writer.toString). But I'd want to avoid buffering and to stream data supplied by Writer.

How to craft a Play Enumerator based on java.io.Writer?


Solution

  • You can implement your own writer that uses a Concurrent.Channel to push data to an enumerator, let's talk code:

    class MyWriter extends java.io.Writer{
    var channel : Concurent.Channel
    def write(x:Array[Char], s:Int, e:Int) = {
      channel.push(x)
    }
    def close() = {
      channel.end()
    }
    def flush() = {
    
    }
    }
    // every time writer.write is used it will push data to the enumeratr
    var writer = new YourWriter();
    val enumerator:Enumerator[Array[Char]]  = Concurrent.unicast[Array[Char]](channel => {writer.channel = channel})