Skip to content

Instantly share code, notes, and snippets.

@shankarshastri
Created May 20, 2017 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shankarshastri/1f68acea55e3358e7b8cf5993a67b91c to your computer and use it in GitHub Desktop.
Save shankarshastri/1f68acea55e3358e7b8cf5993a67b91c to your computer and use it in GitHub Desktop.
AkkHttpChunked.scala
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.marshalling.ToResponseMarshaller
import akka.http.scaladsl.model.{ ContentTypes, HttpEntity }
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives.{ _segmentStringToPathMatcher, complete, get, path }
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
object StreamNumbers extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val toResponseMarshaller: ToResponseMarshaller[Source[Int, Any]] =
Marshaller.opaque { items =>
val data = items.map(item => ChunkStreamPart(item.toString + "\n"))
HttpResponse(entity = HttpEntity.Chunked(ContentTypes.`application/json`, data))
}
def newDataStream(): Stream[Int] = Stream.from(1)
val route =
path("numbers") {
get {
complete {
Source(newDataStream())
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
scala.io.StdIn.readLine()
import system.dispatcher // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.terminate()) // and shutdown when done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment