pekko/akka-docs-dev/rst/scala/code/docs/stream/cookbook/RecipeKeepAlive.scala

78 lines
2.2 KiB
Scala
Raw Normal View History

2014-12-08 17:29:40 +01:00
package docs.stream.cookbook
import akka.stream.ClosedShape
2014-12-08 17:29:40 +01:00
import akka.stream.scaladsl._
2015-04-24 11:45:03 +03:00
import akka.stream.testkit._
2014-12-08 17:29:40 +01:00
import akka.util.ByteString
class RecipeKeepAlive extends RecipeSpec {
"Recipe for injecting keepalive messages" must {
"work" in {
type Tick = Unit
2015-04-24 11:45:03 +03:00
val tickPub = TestPublisher.probe[Tick]()
val dataPub = TestPublisher.probe[ByteString]()
val sub = TestSubscriber.manualProbe[ByteString]()
2014-12-08 17:29:40 +01:00
val ticks = Source(tickPub)
val dataStream = Source(dataPub)
val keepaliveMessage = ByteString(11)
val sink = Sink(sub)
//#inject-keepalive
2015-07-08 10:23:10 +03:00
val tickToKeepAlivePacket: Flow[Tick, ByteString, Unit] = Flow[Tick]
2014-12-08 17:29:40 +01:00
.conflate(seed = (tick) => keepaliveMessage)((msg, newTick) => msg)
val graph = RunnableGraph.fromGraph(FlowGraph.create() { implicit builder =>
import FlowGraph.Implicits._
val unfairMerge = builder.add(MergePreferred[ByteString](1))
2014-12-08 17:29:40 +01:00
// If data is available then no keepalive is injected
2015-07-08 10:23:10 +03:00
dataStream ~> unfairMerge.preferred
ticks ~> tickToKeepAlivePacket ~> unfairMerge ~> sink
ClosedShape
})
2014-12-08 17:29:40 +01:00
//#inject-keepalive
graph.run()
val subscription = sub.expectSubscription()
// FIXME RK: remove (because I think this cannot deterministically be tested and it might also not do what it should anymore)
2015-04-24 11:45:03 +03:00
tickPub.sendNext(())
2014-12-08 17:29:40 +01:00
// pending data will overcome the keepalive
2015-04-24 11:45:03 +03:00
dataPub.sendNext(ByteString(1))
dataPub.sendNext(ByteString(2))
dataPub.sendNext(ByteString(3))
2014-12-08 17:29:40 +01:00
subscription.request(1)
sub.expectNext(ByteString(1))
subscription.request(2)
sub.expectNext(ByteString(2))
2015-09-18 17:17:25 +02:00
// This still gets through because there is some intrinsic fairness caused by the FIFO queue in the interpreter
// Expecting here a preferred element also only worked true accident with the old Pump.
sub.expectNext(keepaliveMessage)
2014-12-08 17:29:40 +01:00
subscription.request(1)
2015-09-18 17:17:25 +02:00
sub.expectNext(ByteString(3))
2014-12-08 17:29:40 +01:00
subscription.request(1)
2015-04-24 11:45:03 +03:00
tickPub.sendNext(())
2014-12-08 17:29:40 +01:00
sub.expectNext(keepaliveMessage)
2015-04-24 11:45:03 +03:00
dataPub.sendComplete()
tickPub.sendComplete()
2014-12-08 17:29:40 +01:00
sub.expectComplete()
}
}
}