Last active
August 29, 2015 13:56
-
-
Save ncornwell/9318019 to your computer and use it in GitHub Desktop.
Combining two different streams at different frequencies using scalaz-stream
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
import scalaz.stream._ | |
object Main extends App { | |
val (qInt, srcInt) = async.queue[Int] | |
val (qString, srcString) = async.queue[String] | |
val repsInt = 5 | |
val repsString = 5 | |
new Thread(new Runnable { | |
def run(): Unit = { | |
(0 until repsInt).foreach(_ => { | |
Thread.sleep(100) | |
val result = (math.random * 100).toInt | |
qInt.enqueue(result) | |
}) | |
qInt.close | |
} | |
}).start() | |
new Thread(new Runnable { | |
def run(): Unit = { | |
(0 until repsString).foreach(_ => { | |
Thread.sleep(300) | |
val result = (math.random * 100).toInt | |
qString.enqueue("String Rep:" + result.toString) | |
}) | |
qString.close | |
} | |
}).start() | |
val result = srcInt | |
.either(srcString) | |
.map(e => e.fold(i => "Int Rep:" + i.toString, s => s)) //arbitrary method to combine streams | |
.runLog | |
.run | |
assert(result.length == (repsInt + repsString)) | |
assert(result.count(_.startsWith("String")) == repsString) | |
assert(result.count(_.startsWith("Int")) == repsInt) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can do the two consumers with:
The first run returns
Task
, the secondrunAsync
takes a callback of typeThrowable \/ A => Unit
. The call torunAsync
will be nonblocking as long as the process itself is nonblocking, which in this case it is since it's built usingawakeEvery
.Another thing you can do in this instance, rather than running the two producers, is to do:
So,
a.drain.merge(b)
will in general runa
just for its effects concurrently with the values ofb
being emitted.Also, the API for queue may change slightly in the near future - we are going to have
enqueue
return aTask
rather than having the side effect directly, which will be useful for implementing a 'nonblocking' finite queue. Of course, nothing would stop you from running thatTask
immediately.