Created
April 4, 2024 22:44
-
-
Save longshorej/ed939ca0ad6218139b20719bc56fd517 to your computer and use it in GitHub Desktop.
akka-streams only occasionally call an expensive function via expand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// suppose that isEnabled is expensive, so we want to call it only once, but otherwise reuse the results | |
// of the previous call. we can use Akka Streams expand operator to effectively repeat the previous | |
// value, and Source.tick to ensure we call only once per second | |
import akka.actor.ActorSystem | |
import akka.stream.scaladsl.{Sink, Source} | |
import scala.concurrent.duration._ | |
import java.util.concurrent.ThreadLocalRandom | |
class Test { | |
implicit val system: ActorSystem = ActorSystem("test") | |
Source | |
.repeat(1) | |
.throttle(4, 1.second) | |
.scan(0)(_ + _) | |
.zip( | |
Source | |
.tick(0.seconds, 5.second, ()) | |
.map(_ => isEnabled()) | |
.expand(Iterator.continually(_)) | |
) | |
.takeWithin(20.seconds) | |
.runWith(Sink.foreach(println)) | |
// an expensive function - only want to call it once per second | |
private def isEnabled(): Boolean = { | |
val result = ThreadLocalRandom.current().nextBoolean() | |
println(s"calculated isEnabled=$result") | |
result | |
} | |
} |
Author
longshorej
commented
Apr 4, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment