DailyJS

DailyJS

The JavaScript blog.


Tagreactive
Featured

java runtimes vert.x nashorn reactive oracle

Vert.x 3.0

Posted on .

Paulo Lopes wrote in with the news that Vert.x 3.0 is out (License: Eclipse/Apache 2.0). Vert.x is a JVM-based toolkit for building applications that supports multiple languages, including JavaScript. It's event driven and non-blocking, so it originally received interest from Node programmers, but it currently seems more popular in the Java community.

Here's an example of a Vert.x web server:

vertx.createHttpServer()  
  .requestHandler(function (req) {
    req.response()
      .putHeader('content-type', 'text/plain')
      .end('Hello from Vert.x!');
}).listen(8080);

Version 3 has a new API designed specifically for building web applications. It's called Vert.x-Web, and it supports routing, body and cookie parsing, authentication, static files, and it has an event bus bridge.

The routing API looks like many other server-side JavaScript web frameworks:

var route = router.route('POST', '/catalogue/products/:productype/:productid/');

route.handler(function(routingContext) {  
  var productType = routingContext.request().getParam('producttype');
  var productID = routingContext.request().getParam('productid');

  // Do something with them...
});

Vert.x 3 has support for MongoDB, Redis, and JDBC. It also supports reactive streams, and it has RxJava style APIs if you want to avoid using too many nested callbacks. The reactive API supports things like converting readable streams to observables (Rx.Observable.fromReadStream), and asynchronous future objects (Rx.observableFuture). Vert.x pushes reactive programming pretty hard, so if reactive programming is your thing then you might want to try it out.

Vert.x's JavaScript engine is Oracle's Nashorn. As far as I know, most of the ES6 features that you'd actually want (like classes) are not yet supported. Nashorn gets updated when the JDK gets updated, so it might be a while before several key ES6 features are ready. I couldn't get Babel working with it, but it seems likely that it could be adapted to work. Someone in the Vert.x community may have already ported an ES6 transpiler.

If you want to read more about Vert.x 3 and Nashorn, I found a recent interview with Tim Fox, the creator of Vert.x, and there's an official Nashorn blog.

Featured

libraries functional modules reactive

most.js: Monadic Reactive Streams

Posted on .

Nick Ts. sent in most.js (GitHub: cujojs/most, License: MIT, npm: most), a reactive programming library designed for working with streams of values and events. You can use it with WebSocket, DOM events, and it should work with fantasy land and Promises/A+.

Let's say you've got an HTML fragment that you want to make dynamic. It should update in real-time based on user input. Here's a snippet:

<form>  
  <input class="x"> + <input class="y"> = <span class="result"></span>
</form>  

The goal is to make the form sum two numbers. Given a simple add function, and a function to cast the form's strings to numbers, a reactive most.js implementation could look like this:

var most = require('most');

var xInput = document.querySelector('input.x');  
var yInput = document.querySelector('input.y');  
var resultNode = document.querySelector('.result');

exports.main = function() {  
  // x represents the current value of xInput
  var x = most.fromEvent('input', xInput).map(toNumber);

  // y represents the current value of yInput
  var y = most.fromEvent('input', yInput).map(toNumber);

  // result is the live current value of adding x and y
  var result = most.combine(add, x, y);

  // Observe the result value by rendering it to the resultNode
  result.observe(renderResult);
};

function add(x, y) {  
  return x + y;
}

function toNumber(e) {  
  return Number(e.target.value);
}

function renderResult(result) {  
  resultNode.textContent = result;
}

The API is different to React and Knockout, but you should be able to follow it. There's a method called fromEvent that can map DOM events to JavaScript functions, then a method called combine that creates a new stream based on the streams from the two inputs. What's cool about this is you could further process the streams with to do things like throttling or tailing the results.

The people behind most.js have made sure it performs well, and there are some promising benchmarks. The library itself is from cujoJS, which is described as a toolkit for building web applications. The most.js readme has some functional and ES6 generators, so if you're interested in seeing what most.js looks like with generators then take a look there.

You can use most.js without worrying too much about what things like monads and functors are, but if you're interested in functional programming in JavaScript then you should try out Fantasy Land Specification.

Featured

functional libraries reactive

ADT Streams

Posted on .

More libraries are starting to blend ideas from functional programming, streams, and reactive programming. Yassine Elouafi sent in ADT Streams (License: MIT, npm: adtstream), a library that offers a stream API using promises and algebraic data types. It has methods for wrapping other streams, like Stream.fromReadable for use with Node's Readable streams, Stream.fromEmitter for objects that extend EventEmitter, and Stream.fromDomEvent for working with DOM events in the browser.

There are utility methods, like Stream.seq for yielding elements from a sequence over time. The blog post, Promises + FP = Beautiful Streams explains each of the library's methods with examples first in Haskell and then in JavaScript. It also has some background on streams and reactive programming:

The basic idea is that you can represent different asynchronous data like events or http responses by an unifying concept called observable collections. Then you can manipulate those collections by standard array operations like map, filter, reduce, forEach ...etc.

By using Yassine's library, you can compose streams with different sources: you can mix events and readable streams with the same API.

The author also wrote From callback to (Future -> Functor -> Monad), which argues why callbacks are not composable and alternative solutions:

With composition, you never hit a wall, because you must always ask yourself "What is the return value of this function?", or put another way "What is the meaning of this thing?"

I don't mind using callbacks in my code. In fact, callbacks are great for things such as representing side effects or event notification, but once your start using them to manage your control flow, you're trapped, why? because they do not compose.

Both of these posts will be of interest to you if you're a JavaScript programmer without much functional or reactive programming experience.

Featured

functional node browser modules libraries reactive

Flyd: Reactive Functional Programming

Posted on .

When I see yet another reactive programming library, I think to myself "that's just not functional enough!" And the libraries that keep me interested in JavaScript are almost always pushing functional practices or static type checking.

Therefore I was interested to see Flyd (GitHub: paldepind/flyd, License: MIT, npm: flyd) by Simon Friis Vindum in my DailyJS inbox today. This project aims to model values that change over time using reactive and functional concepts without adding too much extra baggage.

Flyd is more functional than existing FRP libraries. Instead of methods it gives you curried functions with arguments in the order suitable for partial application. This gives more expressive power and modularity.

The building block in Flyd is streams. You can plug them in wherever a function is expected:

var clicks = flyd.stream();  
document.getElementById('button').addEventListener('click', clicks);  
var messages = flyd.stream();  
webSocket.onmessage = messages;  

Streams can depend on other streams, which is where the functional composition of Flyd comes in.

The author has provided some nice interactive examples that make the library easier to visualise. Take a look at the sum example to get started. And if you're interested in comparing to RxJS, then compare this Flyd code to functionally equivalent RxJS code.

Featured

frameworks libraries reactive react

WebRx, Flummox

Posted on .

WebRx

Oliver Weichhold sent in WebRx (GitHub: oliverw/WebRx, License: MIT), a new MVVM framework built on ReactiveX for JavaScript. It combines ideas from several libraries, including a router inspired by Angular's UI-Router, and bindings inspired by Knockout. It also supports dependency injection, components, modules, and routing.

The choice of patterns and JavaScript idioms means you get an interesting blend of Angular, Knockout, and Rx. If you're an Rx or TypeScript developer then it may appeal to you. It might even work if you're using Knockout with plain old JavaScript but want to move to a framework to aid with your application's architecture.

Flummox

Asaf Katz sent in Flummox (GitHub: acdlite/flummox, License: MIT, npm: flummox) by Andrew Clark. Flummox is a Flux library that provides higher-level encapsulation: you can combine all of your stores, actions, constants, and the dispatcher into a single class. The class has no global references or singletons, which seems ideal for testing. The author argues that this makes isomorphism more straightforward -- imagine being able to load the same module on the client and server without any messy internal dependencies and state.

The primary goal of Flummox is reduce the boilerplate involved in setting up Flux for your application, so the API has been kept as minimal and predictable as possible. It uses Facebook's dispatcher under the hood. It encourages (but does not require) the use of ES6 classes. The state API for stores mirrors the state API for React components. Everything works as you'd probably expect.

Using Flummox with React requires adding event listeners, but Andrew recommends doing this with FluxComponent or fluxMixin.