Like RxJS, but for normal people.
On a recent project, I decided to use RxJS to avoid what would otherwise have quickly become a spaghetti mess of imperative code. But I'm not used to thinking in streams, and found myself fighting the library at every turn. The Reactive mantra that anything can be stream (from this excellent introduction) soon gave way to everything must be a stream. Figuring out how to use Reactive concepts alongside more familiar techniques was beyond me in the limited time I had available before my deadline.
So I did the only sensible thing and wrote my own library, with the following goals:
distinctUntilChangedand friends, you'll know exactly what is going on
npm install --save gurgle
You can import individual functions into your app using this ES6 syntax...
...but for the sake of convenience, we'll do it like this in all of the examples:
This is equivalent to
var g = require('gurgle') if you're old school. (It comes with a UMD build, so you can also use it with an AMD loader or plain ol' script tags.)
You can create a stream of arbitrary values like so:
const stream = g;// All streams have a `push` method, which returns `this`stream;streamvalue; // 'a' – the most recently pushed value// the second and third arguments to `stream.subscribe`// are optional. If a value has been pushed to the stream// the stream is considered to have 'started', and the// callback will be called with the current stream valuestream;// -> 'the value is a'stream;// -> 'the value is b'stream;// -> 'the value is c'// -> 'the value is d'// -> 'cleaning up'// -> 'closing the stream'
Once a stream is closed, you cannot push more values to it, and the subscriber functions will no longer be called.
stream.error(...) will cause any error handlers to be invoked, and will close the stream:
const anotherStream = g;anotherStream;anotherStream;// -> 'oh noes! something went wrong'// -> 'closing the stream'
Gurgle provides convenient ways to create common streams:
// fromAjax – accepts a URL and an options object. Self-closingconst ajaxStream = g;// fromEvent – accepts a DOM node (or `window`) and// an event type. Removes event listener when stream// is closedconst eventStream = g;// fromPromise – creates a stream from a Promise, which// auto-closes once the promise resolvesconst promiseStream = g;// fromGeolocation – watches user's location at a specified interval// or using watchPositionconst geolocationStream = g;// requestAnimationFrame – creates a stream that updates every frame// with a tick valueconst frame = g;// more to come...
In Gurgle, operators on streams are standalone functions that return streams:
const input = g;const mapped = g;const filtered = g;
This works well and is inherently highly composable, but if you prefer chaining, you can do so with the
const input = g;const filtered = input;
Consult the wiki for details about individual operators.