Best Practices

In this chapter we collect general recommendations that have proven to be helpful when working with backpressured streams in general as well as swave in particular.

Prefer def over val

One simple way to deal with the non-reusability of swave’s stream components is to model them as a def rather than a val wherever reuse is desired, e.g. like this:

// the stream of all natural numbers as Strings
def numberStrings = Spout.ints(from = 1).map(_.toString)

// print the first 10
numberStrings.take(10).foreach(println)

// print the 42nd
println(numberStrings.drop(41).drainToHead())

// concatenate the first hundred
val s: Future[String] =
  numberStrings.take(100)
    .drainToMkString(limit = 1000, ", ")

Apart from ensuring that you’ll never see an IllegalReuseException it also has the benefit that parameterizing your higher-level stream constructs becomes trivial (as all that’s required is giving the def a parameter list).