Impl Sink.takeLast operator
Add documentation reformatting Address review comments
This commit is contained in:
parent
2aa333d076
commit
3a92104160
7 changed files with 168 additions and 6 deletions
|
|
@ -23,7 +23,7 @@ import org.reactivestreams.{ Publisher, Subscriber }
|
|||
|
||||
import scala.annotation.unchecked.uncheckedVariance
|
||||
import scala.collection.generic.CanBuildFrom
|
||||
import scala.collection.immutable
|
||||
import scala.collection.{ immutable, mutable }
|
||||
import scala.compat.java8.FutureConverters._
|
||||
import scala.compat.java8.OptionConverters._
|
||||
import scala.concurrent.{ Future, Promise }
|
||||
|
|
@ -216,6 +216,52 @@ import scala.util.{ Failure, Success, Try }
|
|||
override def toString: String = "LastOptionStage"
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERNAL API
|
||||
*/
|
||||
@InternalApi private[akka] final class TakeLastStage[T](n: Int) extends GraphStageWithMaterializedValue[SinkShape[T], Future[immutable.Seq[T]]] {
|
||||
require(n > 0, "n must be greater than 0")
|
||||
|
||||
val in: Inlet[T] = Inlet("takeLastStage.in")
|
||||
|
||||
override val shape: SinkShape[T] = SinkShape.of(in)
|
||||
|
||||
override def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = {
|
||||
val p: Promise[immutable.Seq[T]] = Promise()
|
||||
(new GraphStageLogic(shape) with InHandler {
|
||||
private[this] val buffer = mutable.Queue.empty[T]
|
||||
private[this] var count = 0
|
||||
|
||||
override def preStart(): Unit = pull(in)
|
||||
|
||||
override def onPush(): Unit = {
|
||||
buffer.enqueue(grab(in))
|
||||
if (count < n)
|
||||
count += 1
|
||||
else
|
||||
buffer.dequeue()
|
||||
pull(in)
|
||||
}
|
||||
|
||||
override def onUpstreamFinish(): Unit = {
|
||||
val elements = buffer.result().toList
|
||||
buffer.clear()
|
||||
p.trySuccess(elements)
|
||||
completeStage()
|
||||
}
|
||||
|
||||
override def onUpstreamFailure(ex: Throwable): Unit = {
|
||||
p.tryFailure(ex)
|
||||
failStage(ex)
|
||||
}
|
||||
|
||||
setHandler(in, this)
|
||||
}, p.future)
|
||||
}
|
||||
|
||||
override def toString: String = "TakeLastStage"
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERNAL API
|
||||
*/
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue