UNPKG

rafa

Version:

Rafa.js is a Javascript framework for building concurrent applications.

37 lines (29 loc) 1.47 kB
A Channel implements concurrent message passing (read and write). It allows two disparate objects to push and pull messages at their own pace. A channel is also an enumerator, so it can be passed to streams and anything written to the channel will be pulled into the stream. The stream can then pull values at its own pace (backpressure). A channel can have only one reader subscribed to receive messages at one time, but can have multiple writers pushing values. By default, a channel is not buffered. If a writer attempts to write a value to the channel and there is no reader waiting for values, then the value is dropped and the writer is informed of the issue by a `0` return value. To prevent message loss, the channel can be buffered by setting the size parameter to an integer value greater than 0. All messages will be queued until the size of the buffer hits capacity at which time they will be dropped. To prevent newer messages from being dropped, the action parameter can be set to "rotate", which will drop the oldest values when new values are written. Channels use a ring buffer to store values when the capacity parameter is greater than 0. This make it extremely efficient when writing values even if the buffer is full. <aside> ```js // Rafa.channel(capacity: Int, action: String): Channel var channel = Rafa.channel(); var values = []; channel.read(v => values.push(v)); channel.write(1); channel.write(2); // values: [1]; ``` </aside>